What is the difference between the procedural and object-oriented approaches to accessing mysqli_num_rows() in PHP?
The procedural approach to accessing mysqli_num_rows() in PHP involves using the mysqli_num_rows() function directly with the result set returned by a mysqli_query() call. On the other hand, the object-oriented approach involves calling the mysqli_num_rows() method on the mysqli_result object returned by a query execution method of the mysqli class. The procedural approach is more straightforward for beginners, while the object-oriented approach offers better encapsulation and code organization. Procedural approach:
// Establish database connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Execute query
$result = mysqli_query($conn, "SELECT * FROM table_name");
// Get number of rows
$num_rows = mysqli_num_rows($result);
echo "Number of rows: " . $num_rows;
// Close connection
mysqli_close($conn);
```
Object-oriented approach:
```php
// Establish database connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Execute query
$result = $conn->query("SELECT * FROM table_name");
// Get number of rows
$num_rows = $result->num_rows;
echo "Number of rows: " . $num_rows;
// Close connection
$conn->close();
Related Questions
- What are the potential pitfalls of using nested IF operators in PHP for generating SQL queries?
- What are the potential pitfalls or issues to watch out for when truncating text in PHP?
- How can PHP be used to handle the process of saving invoice items to a temporary database before finalizing and storing them in a permanent database?