mysqli在if-then块内部或外部准备了语句


mysqli prepared statements inside or outside if then blocks

一直在重做网站。升级到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",我将执行最后两个插入中的一个或另一个。因为它们是有条件的,我是否只有在它们被"选中"时才准备它们?

希望我清楚。:-)

仍在学习事先准备好的陈述。

您可以像提议一样有条件地确定准备好的语句。这里没有问题。唯一的问题是,在您的情况下,您需要了解选择了哪个选项,以便知道要绑定多少参数。

话虽如此,在查看代码时,您可能会考虑执行INSERT操作。。像这样选择查询:

INSERT INTO table_1 (field_1, field_2)
SELECT field_1, field_2 FROM table_2
WHERE field_x = ?

因此,您不需要在一个循环中执行一大堆不同的查询。您应该能够通过一个查询执行您想要的操作。

请参阅INSERT上的MySQL文档。。在此处选择语法:http://dev.mysql.com/doc/refman/5.5/en/insert-select.html

因为两个语句之间的参数数量不同,所以在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