在mysql中插入一个PHP false


Insert a PHP false into mysql

我的MySQL表包含一个tinyint(1)值,我用来存储一个真或假的值

我有以下PHP变量:

$name = '';
$description = '';
$active = true;
现在我的SQL查询如下:
$query = "INSERT into my_table (my_name, my_description, active) VALUES ('$name', '$description', $active) ";

只有当$active的值为true时才会起作用。一旦活动变量为false, php将插入一个空字符串,而不是0,因此查询将失败。

在这样的查询中使用false的最佳方法是什么?

我应该手动将false转换为'0'字符串吗?在PHP端使用字符串更好吗?换句话说,声明:$active = '1';或者我能以某种方式让PHP总是将false转换为'0'字符串吗?

谢谢迈克尔。

将变量转换为int:

intval($active)

首先,您的值应该使用mysql_real_escape_string或mysqli_real_escape_string或其他适合您的数据库连接的方法进行转义以避免sql注入然后对于您关于false的特定问题,您可以这样做:

$query = "INSERT into my_table (my_name, my_description, active) VALUES ('$name', '$description', ".($active?1:0) .")";

或将$active转换为int也可以完成工作:

$query = "INSERT into my_table (my_name, my_description, active) VALUES ('$name', '$description', ".((int) $active)).")";

使用mysql_real_escape_string函数…

$query = "INSERT into my_table (my_name, my_description, active) VALUES ('".mysql_real_escape_string($name)."', '".mysql_real_escape_string($description)."', ".mysql_real_escape_string (((int) $active))).")";