Skip to content
PHP Logo

What are some common best practices for handling database access in PHP scripts?

When handling database access in PHP scripts, it is important to follow best practices to ensure security, efficiency, and maintainability. Some common best practices include using prepared statements to prevent SQL injection attacks, closing database connections after use to free up resources, and using error handling to catch and handle any database-related errors.

php
// Establishing a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Checking connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Using prepared statements to prevent SQL injection
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();

// Closing database connection
$conn->close();