我有以下代码:
$var1 = NULL;
$var2 = NULL;
$var3 = NULL;
$var4 = NULL;
/* (...) code for logical flow condition (...) */
/* After the code, only var1 is different
*/
// $var1 = "something"
$query = "INSERT INTO (...) VALUES ('$var1','$var2','$var3','$var4');
这是交易: 所有变量的所有字段都是唯一。代码的问题是数据库没有插入&#34; $ var 2,3,4&#34;的重复值。因为它正在插入vars作为&#39; &#39;而不是NULL。我希望值为NULL BUT 在一个连贯的查询中保留所有内容...如果你可以说,在一种连接中,不要破坏我的逻辑流代码的容易性...... < / p>
我想要
$query = "INSERT INTO (...) VALUES ('$var1','$var2','$var3','$var4');
要
$query = "INSERT INTO (...) VALUES ('$var1',NULL,NULL,NULL);
而不是它是什么:
$query = "INSERT INTO (...) VALUES ('$var1','','','');
那么,在NULL和非NULL时,如何在查询中保持变量呢? Tyvm求助
答案 0 :(得分:2)
您需要测试该值是字符串还是null,并且只在SQL中添加引号(如果它是字符串):
$var1_sql = $var1 === null ? "NULL" : "'$var1'";
$var2_sql = $var2 === null ? "NULL" : "'$var2'";
$var3_sql = $var3 === null ? "NULL" : "'$var3'";
$var4_sql = $var4 === null ? "NULL" : "'$var4'";
$query = "INSERT INTO (...) VALUES ($var1_sql, $var2_sql, $var3_sql, $var4_sql)";
但最好使用准备好的查询。
$query = "INSERT INTO (...) VALUES (?, ?, ?, ?)";
$stmt = $conn->prepare($query);
$stmt->bind_param("ssss", $var1, $var2, $var3, $var4);
$stmt->execute();
答案 1 :(得分:0)
尝试这样的事情:
$var1 = NULL;
$var2 = "'a value'";
$var3 = NULL;
$var4 = "'another val'";
$query = "INSERT INTO (...) VALUES ($var1,$var2,$var3,$var4)";