如果输入字段为空,则尝试使用PHP作为NULL插入。
我有一个默认为NULL的INT字段。这是一个曲棍球运动员输入他们的球衣号码。
如果他们没有球衣号码,那么在我的MySQL数据库中,他们的“球衣”字段应该为空。但是当我mysql_real_escape_string这个值(它是$jersey = NULL)时,它缺省为zero。
我必须将我的字段更改为VARCHAR吗?或者是否有针对mysql_real_escape_string的变通方法
下面是我的插入代码:
sprintf("INSERT INTO players (playerName, playerNumber,)
VALUES
('%s',%d,)",
mysql_real_escape_string($name),
mysql_real_escape_string($number)谢谢你的见解。我在搜索的时候没有找到任何答案。
发布于 2013-10-05 06:45:28
这根本不是mysql_real_escape_string的问题。
而是你创建查询的方式。
对于旧的mysql扩展,唯一的方法是添加一个文字NULL而不是一个变量。
$name = "'".mysql_real_escape_string($name)."'";
$number = is_null($number) ? 'NULL' : intval($number);
$sql = "INSERT INTO players (playerName, playerNumber) VALUES ($name, $number)";或者,如果您想摆脱混乱,可以使用safeMysql
$sql = "INSERT INTO players (playerName, playerNumber) VALUES (?s, ?i)";
$sd->query($sql, $name, $number);在非常令人信服的请求之后,我终于完成了从PHP空值到查询空值的转换。
这将是所有提议的解决方案中最短的代码。
发布于 2013-10-05 06:57:40
sprintf("INSERT INTO players (playerName, playerNumber) VALUES (%s, %s)",
is_null($name) ? 'NULL' : "'".mysql_real_escape_string($name)."'"
is_null($number) ? 'NULL' : "'".mysql_real_escape_string($number)."'"
)https://stackoverflow.com/questions/19191875
复制相似问题