5

我的 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 时才有效。一旦活动变量为假,php 将插入一个空字符串,而不是 0,因此查询将失败。

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

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

谢谢迈克尔

4

3 回答 3

6

将变量转换为 int:

intval($active)
于 2011-12-26T15:25:50.377 回答
5

首先,您的值应该使用 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)).")";
于 2011-12-26T15:25:32.780 回答
0

使用 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))).")";
于 2011-12-26T15:49:58.970 回答