What best practices should be followed when handling database queries and error handling in PHP scripts?
When handling database queries in PHP scripts, it is important to use prepared statements to prevent SQL injection attacks. Additionally, proper error handling should be implemented to catch and handle any database errors that may occur during query execution.
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare a SQL statement using a prepared statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Execute the query
$stmt->execute();
// Bind the result variables
$stmt->bind_result($id, $username, $email);
// Fetch the results
while ($stmt->fetch()) {
echo "ID: " . $id . " Username: " . $username . " Email: " . $email . "<br>";
}
// Close the statement and connection
$stmt->close();
$conn->close();