在 mysqli 准备好的语句中使用空值 [英] using nulls in a mysqli prepared statement
问题描述
在 mysqli 准备好的语句中,NULL 被转换为 ''(在字符串的情况下)或 0(在整数的情况下).我想将它存储为真正的 NULL.有没有办法做到这一点?
In a mysqli prepared statement, a NULL gets turned into '' (in the case of a string) or 0 (in the case of an integer). I would like to store it as a true NULL. Is there any way of doing this?
推荐答案
可以将真正的 NULL 值绑定到准备好的语句(阅读 this).
It's possible to bind a true NULL value to the prepared statements (read this).
实际上,您可以使用 mysqli_bind_parameter 将 NULL 值传递给数据库.只需创建一个变量并将 NULL 值(参见手册页)存储到该变量并绑定它.无论如何对我来说都很棒.
You can, in fact, use mysqli_bind_parameter to pass a NULL value to the database. simply create a variable and store the NULL value (see the manpage for it) to the variable and bind that. Works great for me anyway.
因此它必须是这样的:
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
// person is some object you have defined earlier
$name = $person->name();
$age = $person->age();
$nickname = ($person->nickname() != '') ? $person->nickname() : NULL;
// prepare the statement
$stmt = $mysqli->prepare("INSERT INTO Name, Age, Nickname VALUES (?, ?, ?)");
$stmt->bind_param('sis', $name, $age, $nickname);
?>
这应该会在数据库中插入一个 NULL 值.
This should insert a NULL value into the database.
这篇关于在 mysqli 准备好的语句中使用空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!