What are best practices for handling MySQL connections and queries in PHP scripts?
When working with MySQL connections and queries in PHP scripts, it is important to properly handle connections to the database, execute queries securely to prevent SQL injection attacks, and handle errors effectively to ensure smooth operation of the application.
// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Execute a query securely using prepared statements
$stmt = $conn->prepare("SELECT * FROM table_name WHERE column_name = ?");
$stmt->bind_param("s", $value);
$value = "example_value";
$stmt->execute();
$result = $stmt->get_result();
// Handle errors if query execution fails
if (!$result) {
die("Error executing query: " . $conn->error);
}
// Process the query result
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the connection
$conn->close();