正在重做网站。升级到mysqli,现在我用准备好的语句整理代码和安全。我理解语句应该在foreach循环之外编写,但我想知道条件语句。
[code that decides $table]
foreach ($_POST[$lastvar] as $key => $value) {
[code not relevant to Q]
$sql3 = "SELECT * from $table WHERE titlesid=? and peopleid=?";
$stmt3 = $mysqli->prepare($sql3);
$stmt3->bind_param("ii", $titlesid,$peopleid);
$stmt3->execute();
if ($stmt3->num_rows == 0) {
if ($table == "dhereviewers") {
$sql = "INSERT into $table (titlesid,peopleid) VALUES (?,?)";
} else {
$sql = "INSERT into $table (titlesid,peopleid,billing) VALUES (?,?,?)";
}
$billing++;
[prepare/execute one of the last two statements]
}
}
}
因此,根据'if',我将执行最后两个插入中的一个或另一个。因为它们是有条件的,如果它们被“选中”,我是否只准备它们?
希望我很清楚。 : - )仍在学习准备好的陈述。
答案 0 :(得分:2)
您可以像您提议的那样有条件地确定准备好的陈述。这里没有问题。唯一的问题是,在您的情况下,您需要了解选择了哪个选项,以便了解要绑定的参数数量。
话虽如此,看看你的代码,你可能会考虑像这样执行INSERT .. SELECT查询:
INSERT INTO table_1 (field_1, field_2)
SELECT field_1, field_2 FROM table_2
WHERE field_x = ?
因此您不需要在循环中执行大量不同的查询。您应该能够通过一个查询完成所需的操作。
请参阅有关INSERT ... SELECT语法的MySQL文档:http://dev.mysql.com/doc/refman/5.5/en/insert-select.html
答案 1 :(得分:0)
因为两个语句之间的参数数量不同,所以在if / then / else块中准备和绑定可能会更清楚。
if ($table == "dhereviewers") {
$sql = "INSERT into $table (titlesid,peopleid) VALUES (?,?)";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("ii", $titlesid, $peopleid);
}
} else {
$sql = "INSERT into $table (titlesid,peopleid,billing) VALUES (?,?,?)";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("iii", $titlesid, $peopleid, $billing);
}
}
$stmt->execute();
@MikeBrant有一个很好的观点,在这个例子中,你可以更简单地做到这一点。但这可能取决于您为此问题排除的一些代码。
PS:num_rows
总是报告零行,直到您获取所有行。您可以使用fetch()执行此操作,或使用$mysqli->store_result()
。见http://www.php.net/manual/en/mysqli-stmt.num-rows.php