What are the best practices for retrieving data from a MySQL database using PHP?
When retrieving data from a MySQL database using PHP, it is important to use parameterized queries to prevent SQL injection attacks. Additionally, it is recommended to properly handle errors and exceptions that may occur during the data retrieval process. Finally, consider using prepared statements for improved performance and security.
<?php
// Establish a connection to the MySQL database
$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 and execute a parameterized query to retrieve data
$stmt = $conn->prepare("SELECT * FROM table WHERE column = ?");
$stmt->bind_param("s", $value);
$value = "example";
$stmt->execute();
// Bind the result to variables and fetch the data
$stmt->bind_result($col1, $col2);
while ($stmt->fetch()) {
echo "Column 1: " . $col1 . " - Column 2: " . $col2 . "<br>";
}
// Close the statement and connection
$stmt->close();
$conn->close();
?>