Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prepared statements fetch_assoc php mysqli

I'm having problems with listing out comments with prepared statements. Any ideas?

Here is my code:

$fetchComments = $cnx -> prepare("SELECT comment FROM comments WHERE video_id=? LIMIT 1");
$fetchComments -> bind_param('s', $row['id']);
$fetchComments -> execute();
$fetchComments -> store_result();
$fetchComments -> bind_result($vid_comment);
if ($fetchComments -> num_rows > 0) {
    whike ($row = mysqli_fetch_assoc($vid_comment)){
    echo $row['comment'];
    }
}
like image 734
sixli Avatar asked Jun 09 '13 19:06

sixli


People also ask

What is prepared statement in MySQLi?

A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency. Prepared statements basically work like this: Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled "?").

Can we use prepared statement for select query in PHP?

You must always use prepared statements for any SQL query that would contain a PHP variable. To do so, always follow the below steps: Create a correct SQL SELECT statement. Test it in mysql console/phpmyadmin if needed.

What is result -> Fetch_assoc ()?

Definition and Usage. The fetch_assoc() / mysqli_fetch_assoc() function fetches a result row as an associative array. Note: Fieldnames returned from this function are case-sensitive.

What is the difference between Fetch_assoc and Fetch_array?

fetch_array returns value with indexing. But Fetch_assoc just returns the the value. here array location 0 contains 11 also this location name is 'id'. means just returns the value.


1 Answers

[For some unknown (and really weird) reason] you cannot use fetch_assoc on mysqli_stmt object.
you need to get mysqli result resource first with mysqli_get_result().

Also please name your variables consistently. Mysqli statement has nothing to do with your comments and knows nothing of them, nor contain them. It's just a mysqli statement object.

$stmt->execute();
$res = $stmt->get_result(); // here you go
while ($row = mysqli_fetch_assoc($res)) {
    echo $row['comment'];
}

Though you never can tell whether this function would be available with mysqli or not.

like image 148
Your Common Sense Avatar answered Sep 27 '22 17:09

Your Common Sense