What are the best practices for structuring PHP scripts to handle database connections and queries efficiently?
To handle database connections and queries efficiently in PHP scripts, it is recommended to use PDO (PHP Data Objects) for database access, prepare statements to prevent SQL injection attacks, and close connections after use to free up resources.
// Establish a database connection using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
// Prepare and execute a query using PDO prepared statements
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(['id' => 1]);
$results = $stmt->fetchAll();
// Close the database connection
$pdo = null;
Keywords
Related Questions
- What common error messages can occur when using the move_uploaded_file() function in PHP?
- Is there a recommended way to handle file downloads in PHP to ensure the downloaded files are intact and usable?
- What is the purpose of the preg_replace function in PHP and how is it used in the provided code snippet?