How can PHP and JavaScript functions be coordinated to display error messages or notifications based on database query results?
When a database query is executed in PHP, the result can be checked to determine if there was an error or if the query returned no results. By using PHP to handle the database query and JavaScript to display error messages or notifications on the front end, a coordinated approach can be achieved. PHP can set a variable based on the query result, which can then be passed to JavaScript to display the appropriate message to the user.
```php
// Perform a database query
$query = "SELECT * FROM users WHERE username = 'john_doe'";
$result = mysqli_query($connection, $query);
// Check if the query was successful
if ($result) {
// Check if any rows were returned
if (mysqli_num_rows($result) > 0) {
// Process the query results
} else {
// Set an error message if no results were found
$error_message = "No results found.";
}
} else {
// Set an error message if there was an error with the query
$error_message = "Error executing query: " . mysqli_error($connection);
}
// Pass the error message to JavaScript
echo "<script>let errorMessage = '" . $error_message . "';</script>";
```
In this code snippet, we first perform a database query to select a user with the username 'john_doe'. We then check if the query was successful and if any rows were returned. Depending on the outcome, we set an appropriate error message. Finally, we echo a JavaScript script that assigns the error message to a variable, which can then be used to display the message on the front end.