What are common pitfalls when using mysqli_connect in PHP scripts?
One common pitfall when using mysqli_connect in PHP scripts is not handling connection errors properly. It is important to check if the connection was successful and handle any potential errors that may occur. Another pitfall is not securely storing database credentials, which can lead to security vulnerabilities. It is recommended to store credentials in a separate configuration file outside of the web root.
// Correct way to use mysqli_connect with error handling and secure credential storage
$host = "localhost";
$username = "username";
$password = "password";
$database = "database";
// Create connection
$conn = mysqli_connect($host, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}