What are common pitfalls when setting up database connections in PHP scripts?
Common pitfalls when setting up database connections in PHP scripts include hardcoding sensitive information such as usernames and passwords directly in the script, not properly sanitizing user input to prevent SQL injection attacks, and not properly handling connection errors. To address these issues, it is recommended to store database credentials in a separate configuration file outside of the web root, use prepared statements or parameterized queries to prevent SQL injection, and implement error handling to gracefully handle connection errors.
<?php
// Include database configuration file
include 'config.php';
// Create a database connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Related Questions
- How can functions like mb_detect_encoding() be used effectively to determine the character encoding of strings in PHP?
- What are some best practices for structuring PHP functions to handle pricing calculations efficiently?
- How can PHP developers optimize their code to ensure it is compatible with different versions of MySQL servers?