What are some best practices for handling database connections and queries in PHP scripts?
When handling database connections and queries in PHP scripts, it is important to establish a secure and efficient connection to the database, properly sanitize user input to prevent SQL injection attacks, and handle errors gracefully to avoid exposing sensitive information. One best practice is to use prepared statements to safely execute queries with user input.
// Establish a database connection
$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 query using prepared statements
$stmt = $conn->prepare("SELECT * FROM table WHERE column = ?");
$stmt->bind_param("s", $value);
$value = "input_value";
$stmt->execute();
$result = $stmt->get_result();
// Fetch results
while ($row = $result->fetch_assoc()) {
// Process results
}
// Close statement and connection
$stmt->close();
$conn->close();