What are the best practices for handling MySQL connections and queries in PHP 5.x to ensure optimal performance and security?
To ensure optimal performance and security when handling MySQL connections and queries in PHP 5.x, it is recommended to use prepared statements to prevent SQL injection attacks and to properly close connections after use to avoid resource leaks.
// Establish a MySQL connection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Prepare a SQL query using a prepared statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Execute the query
$username = "example";
$stmt->execute();
// Bind the results to 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();
$mysqli->close();
Related questions
-
session variables value deduction PHP forms
-
PHP classes arguments parameters
-
PHP array foreach loop