How can the num_rows property be utilized to improve the logic for checking existing records before inserting or updating in PHP?

When inserting or updating records in a database using PHP, it is important to check if a record already exists before proceeding to avoid duplicate entries. The num_rows property can be utilized to check if a query returns any existing records. By checking the num_rows value, you can determine whether to insert a new record or update an existing one accordingly.

// Check if record exists before inserting or updating
$query = "SELECT * FROM table_name WHERE column_name = 'value'";
$result = $mysqli->query($query);

if ($result->num_rows > 0) {
    // Update existing record
    $updateQuery = "UPDATE table_name SET column_name = 'new_value' WHERE column_name = 'value'";
    $mysqli->query($updateQuery);
} else {
    // Insert new record
    $insertQuery = "INSERT INTO table_name (column_name) VALUES ('value')";
    $mysqli->query($insertQuery);
}