How can the num_rows and affected_rows functions in MySQLi be effectively utilized to validate query results in PHP scripts?
To validate query results in PHP scripts, the num_rows function can be used to determine the number of rows returned by a SELECT query, while the affected_rows function can be used to determine the number of rows affected by an INSERT, UPDATE, DELETE, or REPLACE query. By comparing the values returned by these functions to expected values, you can validate the success of your queries in PHP scripts.
// Assuming $mysqli is your MySQLi connection object
// Execute a SELECT query
$result = $mysqli->query("SELECT * FROM table_name");
if ($result->num_rows > 0) {
// Query was successful
} else {
// Query did not return any rows
}
// Execute an INSERT, UPDATE, DELETE, or REPLACE query
$mysqli->query("INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')");
if ($mysqli->affected_rows > 0) {
// Query was successful
} else {
// Query did not affect any rows
}