Php和Mysqli - 你可以在没有WHERE子句的SELECT子句上使用预准备语句吗?

时间:2017-01-09 16:27:19

标签: php mysqli

SELECT id, title, posted, duration, thumbnail, email, first_name
FROM customers

3 个答案:

答案 0 :(得分:1)

以下是一个简短的示例(评论时间太长),因为您使用的是MySQLi:

面向对象的风格:

/* prepare query */
$stmt = $mysqli->prepare("SELECT id, title, posted, duration, thumbnail, email, first_name FROM customers");

/* execute query */
$stmt->execute();

程序样式($conn是数据库连接):

/* prepare */
$stmt = mysqli_prepare($conn, "SELECT id, title, posted, duration, thumbnail, email, first_name FROM customers");

/* execute query */
mysqli_stmt_execute($stmt);

答案 1 :(得分:1)

由于您没有明显的理由准备此声明,即您没有说您希望在此脚本中多次运行此查询,并且您没有将参数绑定到查询的占位符,您只需使用mysqli_query()像这样

$sql = 'SELECT id, title, posted, duration, thumbnail, email, first_name
        FROM customers';

$result = mysqli_query($con, $sql);

while ( $row = $result->fetch_assoc() ) {
    echo $row['id'];   // or whatever
}
  

请记住,您不能将占位符?用于列名或表名,在此mysqli_prepare() $('#event tr').each(function() { var td= $(this).find("td"); var _this=this; $(td).each(function() { var text = $(this).text(); if(text=='' || text==null|| typeof text=='undefined'){ $(_this).hide(); } }); }); 中,如果这是您最终要做的事情,就像@ Fred-ii-一样一直在暗示

答案 2 :(得分:1)

发布为社区维基。

没有什么可以阻止你使用prepare()(在MySQLi_中),因为它是有效的。

你不能这样做,并举几个例子:

  • SELECT col1, col2, col3 FROM ?
  • SELECT ?,?,? FROM ?
  • SELECT ?,?,? FROM table

如果您计划/设想这样做,因为这将构成一个表格/列的约束,这在准备好的陈述中是不允许的,就像我们希望它能够起作用一样。

然而,没有什么可以阻止你使用所谓的"安全列表"。

以下是一些参考文献:

有关使用prepare()而不是query()的内容,请参阅以下相关问题的答案: