我正在通过 php 使用 mysql 数据库。
我有一个表,其中有些值为 NULL
我在 php 中选择这些值:
$opponentInv = db_execute("Select * from inventoryon where playerid = ".$defendid.";");
$opponentInv = mysql_fetch_assoc($opponentInv);
然后我将这些值插入到另一个表中:
db_execute("INSERT INTO `inventoryCombat` (`attackid` ,`defendid` ,`money` ,`item1` ,`item2` ,`item3`, `item4` ,`item5` ,`item6`, `time`)VALUES ('".$attackid."', '".$defendid."', '".$opponentInv["money"]."', '".$opponentInv["item1"]."', '".$opponentInv["item2"]."', '".$opponentInv["item3"]."', '".$opponentInv["item4"]."', '".$opponentInv["item5"]."', '".$opponentInv["item6"]."', '".$time."');");
问题是,当我将值插入第二个表时,它们总是以 0 出现。inventoryCombat 表中的值应该为 NULL(它们在 inventoryon 表中)时为 0。该表设置为接受 NULL 作为值。
最佳答案
首先,我强烈建议您使用 prepared statements而不是构建文字 SQL 字符串。这不仅是一种更好的做法,而且可以帮助您编写更多 secure应用程序,它还可以正确处理 NULL 值,而无需任何额外工作。
如果您想继续使用您当前使用的方法,那么您将需要显式检查未定义的值并将字符串“NULL”插入到您的 SQL 中。换句话说,您需要这样做:
INSERT INTO inventoryCombat (item1) VALUES (NULL);
而不是你现在正在做的:
INSERT INTO inventoryCombat (item1) VALUES ('');
如果仍然不起作用,请仔细检查您尝试插入 NULL 的字段是否设置为允许 NULL 值。您可以使用 SHOW CREATE TABLE inventoryCombat
来执行此操作。
我还建议规范化您的数据库。具有名为 item1
、item2
、item3
等的列是糟糕设计的标志。例如,您当前的设计会使执行诸如“有多少玩家拥有元素 X?”之类的简单查询变得更加复杂。或“将元素 X 添加到玩家 P,除非她已经持有 6 件元素”。
关于php - MySQL - null = 0 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4242995/