Php – thesqli prepared statement , how to loop the result set

MySQLPHPprepared-statementsql-injection

I was researching about mysqli prepared statements and i have 2 questions about it.

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']. So,

Are they any pros/cons using either of the 2 methods to loop the result set?
If there's no difference, then why bother binding the result using $stmt->bind_result in the first place? What's the point if i can use $row = $stmt->fetch() instead?

Here's my other question:

  • $stmt->free_result(); frees what exactly? the prepare() or the store_result() or else ?
  • $stmt->close; what am i closing exactly? the stmt_init() or the prepare() or else?

Hopefully your answers will make me understand better prepared statements so i can build something safe…

Thanks

Best Answer

  • $stmt->free_result() does pretty much what the name says: it frees the memory associated with a result.

  • $stmt->close closes the statement handle (the cursor actually), making it impossible to loop through the result set (again).

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. When closed you cannot use the result set anymore, or reuse it and when php dies, memory is freed anyway.

Related Topic