What are the recommended database connection methods in PHP, and why is the use of mysqli or PDO preferred over the older mysql functions?
The recommended database connection methods in PHP are mysqli and PDO. These methods provide better security features such as prepared statements to prevent SQL injection attacks. It is preferred to use mysqli or PDO over the older mysql functions because they offer improved performance, support for more database drivers, and are actively maintained by the PHP community.
// Using PDO to connect to a database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
Related Questions
- What are the best practices for securely handling user input and database queries in PHP to prevent SQL injection vulnerabilities?
- What are some best practices for handling header warnings related to session_start() in PHP?
- What potential issue might be causing the posted data not to be updated in the database?