Is using mysqli_num_rows() a cleaner and more reliable way to check for the number of rows returned by a SELECT query in PHP?
Using mysqli_num_rows() is a cleaner and more reliable way to check for the number of rows returned by a SELECT query in PHP compared to other methods like counting the result array. It directly returns the number of rows fetched from the database, making it more efficient and accurate.
// Establish database connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Execute SELECT query
$result = $conn->query("SELECT * FROM table_name");
// Check if rows were returned
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Column 1: " . $row["column1"]. " - Column 2: " . $row["column2"]. "<br>";
}
} else {
echo "0 results";
}
// Close connection
$conn->close();
Keywords
Related Questions
- What is the best practice for setting up a cron job in Plesk for a PHP script?
- How can PHP developers troubleshoot and resolve issues related to cookie handling when accessing external websites?
- What are the potential issues with using session variables in PHP, especially when it comes to overwriting values?