wordman wordman - 3 months ago 53
PHP Question

Does SELECT COUNT(*) work with MySQLi prepared statements?

I'm working on a test page and am using MySQLi prepared statements in my queries after reading they make my code safe from SQL injection. I have been successful with prepared statements so far with retrieving data from my DB, that all works great.

What I want to do now is count the number of galleries within a project using SELECT COUNT(*). That's it.

Without using a prepared statement, my old query looked like this:

// count number of galleries per project
$conn = dbConnect('query');
$galNumb = "SELECT COUNT(*) FROM pj_galleries WHERE project = {$pjInfo['pj_id']}";
$gNumb = $conn->query($galNumb);
$row = $gNumb->fetch_row();
$galTotal = $row[0];

But for all my reading and searching the internet, I can not find out the proper way to write this as a prepared statement.


You may be over-thinking things, because it's not different than any other prepared statement:

$conn = new mysqli;
$galNumb = "SELECT COUNT(*) FROM pj_galleries WHERE project = ?";
$stmt = $conn->prepare($galNumb);
$stmt->bind_param('i', $pjInfo['pj_id']);
$gNumb = $stmt->execute();