What is the importance of using error_reporting and mysql_error() functions in PHP scripts?
Using error_reporting and mysql_error() functions in PHP scripts is important for debugging and troubleshooting purposes. error_reporting allows you to control the level of error reporting in your script, helping you identify and fix any issues that may arise. mysql_error() function can be used to retrieve the error message associated with the most recent MySQL operation, providing valuable information to help pinpoint the cause of database-related errors.
<?php
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check for connection errors
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Perform MySQL query
$result = $mysqli->query("SELECT * FROM table");
// Check for query errors
if (!$result) {
die("Query failed: " . $mysqli->error);
}
// Process query results
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close database connection
$mysqli->close();
?>