I'm a bit new to the mysqli prepared statement and I would like to use fetch_array to return the results AND also return num_rows as an array value.
I have something like this
function getCategories($dbh, $catId)
{
$data = array();
$s = "SELECT id, title FROM categories WHERE parent_id = ?";
if ($stmt = mysqli_prepare($dbh, $s)) {
mysqli_stmt_bind_param($stmt, "i", $catId);
mysqli_stmt_execute($stmt);
if (mysqli_stmt_errno($stmt)) {
exit(mysqli_stmt_error($stmt));
}
mysqli_stmt_store_result($stmt);
$count = mysqli_stmt_num_rows($stmt)) {
if ($count) {
$data['count'] = $count;
$result = mysqli_stmt_get_result($stmt);
while ($r = mysqli_fetch_assoc($result)) {
$data[] = $r;
}
}
return $data;
} else {
exit(mysqli_error($dbh));
}
}
It seems that I cannot use mysqli_stmt_store_result and mysqli_stmt_get_result().
The store_result function seems to give a boolean and then I get this error: "mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given"
Hope this makes sense. Any help would be really appreciated.
Updated:
function getCategories($dbh, $catId)
{
$data = array();
$s = "SELECT id, title FROM categories WHERE parent_id = ?";
if ($stmt = mysqli_prepare($dbh, $s)) {
mysqli_stmt_bind_param($stmt, "i", $catId);
mysqli_stmt_execute($stmt);
if (mysqli_stmt_errno($stmt)) {
exit(mysqli_stmt_error($stmt));
}
$result = mysqli_stmt_get_result($stmt);
$data['count'] = $result->num_rows;
while ($r = mysqli_fetch_assoc($result)) {
$data[] = $r;
}
return $data;
} else {
exit(mysqli_error($dbh));
}
}