我正试图使用mysqli_query从PHP向mysql插入NULL。
我的代码如下,我想在$chq_date
:中插入Null
$query_string = "INSERT INTO inward_credit
(custi_id_fk, driver_id_fk, today_date, amount, mode, cheque_date, cheque_no)
VALUES
('$cust_id1', '$driver_id1', '$today_date', '$credit_collected', '$mode', '$chq_date', '$cheque_number')";
$insert_credit = mysqli_query($con, $query_string);
我试过
$chq_date = "";
导致第1行"cheque_date"列的日期值"不正确
$chq_date = '';
导致第1行"cheque_date"列的日期值"不正确
$chq_date = 'NULL';
错误的日期值:第1行"cheque_date"列为"NULL"
$chq_date = "NULL";
错误的日期值:第1行"cheque_date"列为"NULL"
DB是
CREATE TABLE IF NOT EXISTS `inward_credit` (
`id` int(11) NOT NULL,
`custi_id_fk` int(11) NOT NULL,
`driver_id_fk` int(11) NOT NULL,
`today_date` date NOT NULL,
`amount` float(50,2) NOT NULL,
`mode` int(1) NOT NULL,
`cheque_date` date DEFAULT NULL,
`cheque_no` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
`last_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
您没有插入null,而是插入了一个字符串,其中包含字符N
、U
等:
$null_val = 'NULL';
$sql = "INSERT .... VALUES ('$null_val')";
^---------^----
由于上面指出的引号总是存在,因此您永远无法插入实际的sql null。删除引号可以让DB的解析器将字符串null视为sql null。
列的默认值是NULL
,因此它不必在INSERT
语句中。
$query_string = "INSERT INTO inward_credit
(custi_id_fk, driver_id_fk, today_date, amount, mode, cheque_no)
VALUES
('$cust_id1', '$driver_id1', '$today_date', '$credit_collected', '$mode', '$cheque_number')";
$insert_credit = mysqli_query($con, $query_string);
编辑
如果要插入NULL
,请使用以下命令;
- 不要引用变量
$chq_date
,因为这会使NULL
成为字符串。参见Marc B的回答
//if/else logic.
if(<<what>>) {
$chq_date = "2014/09/09";
} else {
$chq_date = "NULL";
}
$query_string = "INSERT INTO inward_credit
(custi_id_fk, driver_id_fk, today_date, amount, mode, cheque_date, cheque_no)
VALUES
('$cust_id1', '$driver_id1', '$today_date', '$credit_collected', '$mode', $chq_date, '$cheque_number')";
$insert_credit = mysqli_query($con, $query_string);
尝试不带引号的NULL
:
$query_string =
"INSERT INTO inward_credit (custi_id_fk, driver_id_fk, today_date, amount, mode, cheque_date, cheque_no)
VALUES ('$cust_id1', '$driver_id1', '$today_date', '$credit_collected', '$mode', $chq_date, '$cheque_number')"
此外,在tale定义中,DEFAULT NULL
是多余的(NULL是sql中的默认值,因此当您不需要NULL时,必须指定NOT NULL)。
在表中,默认值为NULL。所以不需要插入
$query_string = "INSERT INTO inward_credit
(custi_id_fk, driver_id_fk, today_date, amount, mode, cheque_no)
VALUES
('$cust_id1', '$driver_id1', '$today_date', '$credit_collected', '$mode', '$cheque_number')";
$insert_credit = mysqli_query($con, $query_string);
但如果你想明确地插入null,你可以尝试
$query_string = "INSERT INTO inward_credit
(custi_id_fk, driver_id_fk, today_date, amount, mode, cheque_date, cheque_no)
VALUES
('$cust_id1', '$driver_id1', '$today_date', '$credit_collected', '$mode', NULL, '$cheque_number')";
$insert_credit = mysqli_query($con, $query_string);