What are the best practices for handling MySQL queries in PHP?
When handling MySQL queries in PHP, it is important to use prepared statements to prevent SQL injection attacks and improve performance. Prepared statements separate SQL logic from data input, making it safer and more efficient to execute queries.
// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Prepare a SQL statement using a prepared statement
$stmt = $mysqli->prepare("SELECT * FROM table WHERE column = ?");
// Bind parameters to the prepared statement
$stmt->bind_param("s", $value);
// Execute the prepared statement
$stmt->execute();
// Bind result variables
$stmt->bind_result($result);
// Fetch results
while ($stmt->fetch()) {
echo $result;
}
// Close the statement and connection
$stmt->close();
$mysqli->close();