What best practice should be followed when connecting to a MySQL database in PHP?
When connecting to a MySQL database in PHP, it is best practice to use prepared statements to prevent SQL injection attacks. Prepared statements separate SQL logic from user input, making it safer to execute queries. This method helps to sanitize user input and protect against malicious SQL queries.
// Establishing a connection to the MySQL database using prepared statements
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Using prepared statements to execute queries
$stmt = $conn->prepare("SELECT * FROM table WHERE column = ?");
$stmt->bind_param("s", $columnValue);
// Set parameters and execute
$columnValue = "value";
$stmt->execute();
// Process the results
// Close the statement and connection
$stmt->close();
$conn->close();