简体   繁体   English

mysqli编写语句,如何循环结果集

[英]mysqli prepared statement , how to loop the result set

I was researching about mysqli prepared statements and i have 2 questions about it. 我正在研究有关mysqli准备好的陈述,我有两个问题。

As i was reading, i figure out that the order of execution of a prepared statement looks something like the following: 在我阅读时,我发现准备好的语句的执行顺序如下所示:

$sql = 'SELECT image_id, filename, caption FROM images WHERE image_id = ?';

// connect to the database
$conn = ....

$stmt = $conn->stmt_init();

$stmt->prepare($sql);

$stmt->bind_param('i', $id);

$stmt->execute();

$stmt->bind_result($image_id, $filename, $caption);

// optional: get total of records in the result set
$stmt->store_result();
$numRows = $stmt->num_rows;

// loop through the result set
while ($stmt->fetch()) {
    // code goes here...
}

or 

// fetch the result for one record
$stmt->fetch()

// free & close
$stmt->free_result();
$stmt->close;

$conn->close();

Here's my first question: 这是我的第一个问题:

As i was reading, it also mentions the following: 在我阅读时,它还提到了以下内容:

If you don't bind the result to variables, use $row = $stmt->fetch(), and access each variable as $row['column_name']. 如果未将结果绑定到变量,请使用$ row = $ stmt-> fetch(),并将每个变量作为$ row ['column_name']访问。 So, 所以,

Are they any pros/cons using either of the 2 methods to loop the result set? 使用2种方法中的任何一种循环结果集是否有任何优缺点? If there's no difference, then why bother binding the result using $stmt->bind_result in the first place? 如果没有区别,那么为什么首先要使用$ stmt-> bind_result来绑定结果呢? What's the point if i can use $row = $stmt->fetch() instead? 如果我可以使用$ row = $ stmt-> fetch()代替什么呢?

Here's my other question: 这是我的另一个问题:

  • $stmt->free_result(); $ stmt-> free_result(); frees what exactly? 什么准确地解放了? the prepare() or the store_result() or else ? prepare()或store_result()还是其他?
  • $stmt->close; $ stmt->关闭; what am i closing exactly? 我到底在做什么? the stmt_init() or the prepare() or else? stmt_init()或prepare()还是其他?

Hopefully your answers will make me understand better prepared statements so i can build something safe... 希望你的答案能让我理解更准备好的陈述,这样我才能建立安全的东西......

Thanks 谢谢

  • $stmt->free_result() does pretty much what the name says: it frees the memory associated with a result. $ stmt-> free_result()几乎与名称相同:它释放与结果相关的内存。

  • $stmt->close closes the statement handle (the cursor actually), making it impossible to loop through the result set (again). $ stmt-> close关闭语句句柄(实际是光标),使得无法循环遍历结果集(再次)。

Although the manual states: 'You should always free your result with mysqli_free_result(), when your result object is not needed anymore', common practice is not to use free_result and close on a statement. 虽然手册指出:“你应该总是用mysqli_free_result()释放你的结果,当你的结果对象不再需要时”,通常的做法是不要使用free_result并关闭语句。 When closed you cannot use the result set anymore, or reuse it and when php dies, memory is freed anyway. 关闭时,你不能再使用结果集,或者重用它,当php死掉时,无论如何都要释放内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM