What best practices should be followed when handling MySQL queries in PHP scripts to avoid errors like "supplied argument is not a valid MySQL resource"?
When handling MySQL queries in PHP scripts, it is essential to ensure that the connection to the database is established before executing any queries. This error often occurs when a query is executed without a valid MySQL resource, typically due to a failed connection or query execution. To avoid this error, always check the connection status before executing queries and handle any potential errors gracefully.
// Establish a connection to the MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check if the connection is successful
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Execute a sample query
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);
// Check if the query was successful
if (!$result) {
die("Query failed: " . mysqli_error($connection));
}
// Process the query result
while ($row = mysqli_fetch_assoc($result)) {
// Handle the query result
}
// Close the connection
mysqli_close($connection);