Are there alternative methods to mysql_num_rows() in PHP that can provide better error handling and result validation in MySQL queries?
When using mysql_num_rows() in PHP to get the number of rows returned by a MySQL query, it lacks proper error handling and result validation. To improve this, you can use the mysqli extension in PHP which provides better error handling and result validation capabilities.
// Connect to MySQL database using mysqli
$connection = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
// Run a query
$query = "SELECT * FROM table";
$result = $connection->query($query);
// Check for errors
if (!$result) {
die("Error in query: " . $connection->error);
}
// Get number of rows
$num_rows = $result->num_rows;
// Output number of rows
echo "Number of rows: " . $num_rows;
// Close connection
$connection->close();