Get Number of Affected Rows
Runs a targeted procedural mysqli update and returns the number of rows changed by that statement.
Purpose
Runs a targeted procedural mysqli update and returns the number of rows changed by that statement.
Snippet details
ContextDatabaseLevelProductionCopy-and-paste statusMarked safe after review.Categories
- Forms and Validation
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Get Number of Affected Rows.
*
* Purpose:
* Demonstrates how to read the number of rows changed by a prepared mysqli
* UPDATE statement.
*
* @param mysqli $connection Open mysqli connection.
* @param string $fleet_status Status value to assign.
* @param string $fleet_zone Zone used to target rows.
* @return array Affected-row count and status message.
*/
function ogSnippetGetAffectedRows(mysqli $connection, string $fleet_status, string $fleet_zone): array {
$fleet_status = trim($fleet_status);
$fleet_zone = trim($fleet_zone);
if ($fleet_status === '' || $fleet_zone === '') {
return array('success' => false, 'affected_rows' => 0, 'message' => 'Fleet status and zone are required.');
}
$sql = 'UPDATE fleet_registry SET status = ?, updated_at = NOW() WHERE patrol_zone = ?';
$statement = mysqli_prepare($connection, $sql);
if ($statement === false) {
return array('success' => false, 'affected_rows' => 0, 'message' => 'Fleet update could not be prepared.');
}
mysqli_stmt_bind_param($statement, 'ss', $fleet_status, $fleet_zone);
$executed = mysqli_stmt_execute($statement);
if ($executed === false) {
mysqli_stmt_close($statement);
return array('success' => false, 'affected_rows' => 0, 'message' => 'Fleet update failed.');
}
$affected_rows = mysqli_stmt_affected_rows($statement);
mysqli_stmt_close($statement);
return array(
'success' => true,
'affected_rows' => $affected_rows,
'message' => $affected_rows.' row(s) changed.'
);
}
/*
$result = ogSnippetGetAffectedRows($connection, 'Stargate locked', 'Pegasus');
print_r($result);
*/