kikinet kikinet - 1 year ago 58
MySQL Question

How to get num rows from prepared (update) statement executed in foreach

Imagine this code:

if ($stmt = $conn->prepare("UPDATE courses SET courses_price = ? WHERE id_courses = ?")) {
foreach ($_POST as $id => $price) {
$stmt->bind_param('ii', $price, $id);
if ($stmt->num_rows === 0) {
echo 'not affected';
} else {
echo 'affected';


Why num_rows alway returns 0? And yes, I know it counts only afftected rows.. One row is affected always.

Is there a problem with the foreach loop? Or is there a different way how to get number of affected rows?

Answer Source

What? It was SO simple? ... Thank you, can you put it as answer? I will accept it – kikinet

As requested by the OP:

num_rows() is for SELECT, not UPDATE.

What you want to use is affected_rows().


From the manual on affected_rows():

Object oriented style
int $mysqli->affected_rows;

Procedural style
int mysqli_affected_rows ( mysqli $link )