Search code examples
phpmysqlifetch

What does mysqli_stmt_fetch in php do?


I don't understand the concept of the fetch function.

I am doing a tutorial from 'PHP Solutions' book and i am using MySQL Improved to update something in the database.

Here is the code:

$sql = 'SELECT article_id, title, article FROM journal WHERE article_id = ?';
$stmt = $conn->stmt_init();
$stmt->prepare($sql);
$stmt->bind_param('i', $_GET['article_id']);                    
$stmt->bind_result($article_id, $title, $article); 
//execute the query, and fetch the result
$stmt->execute(); 
$stmt->fetch();

So what is the fetch actually doing? I thought the execute() function is sending the information to the database and then it returns a true/false value to the $OK variable.

Is fetch() storing something in $stmt? Anybody have any idea what it is doing?


Solution

  • mysqli_stmt_fetch fetches the current row from the resultset and assigns the row values to variables previously bound to the prepared statement with mysqli_stmt_bind_result.

    Which means that you must call $stmt->bind_result(...); first, as it can be seen in the example from the man page.

    Note that nowadays using mysqli_stmt_fetch is considered inconvenient. Either use mysqli_stmt_get_result followed by familiar mysqli_fetch_* functions, or even avoid the entire bind param hassle with mysqli_execute_query().