在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值绑定到准备好的语句(请阅读
I know this is an old thread, but 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屋!