Skip to content

Instantly share code, notes, and snippets.

@domantasg
Created August 3, 2017 11:11
Show Gist options
  • Save domantasg/2ab6d40f6771a50e93b8ea11bb97341c to your computer and use it in GitHub Desktop.
Save domantasg/2ab6d40f6771a50e93b8ea11bb97341c to your computer and use it in GitHub Desktop.
<?php
$servername = "mysql.hostinger.com";
$username = "u266072517_user";
$database = "u266072517_name";
$password = "buystuffpwd";
// Create a new connection to the MySQL database using PDO
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
@Pen-y-Fan
Copy link

Pen-y-Fan commented Aug 4, 2019

The above example is the OOP method to connect using MySQLi. See https://www.w3schools.com/php7/php7_mysql_connect.asp for an example of correct connection methods for PDO. The above example is the equivalent of “Example (MySQLi Object-oriented)”.

A PDO connection should be:

$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);

// ....

w3scools gives an example using a try-catch block, but this isn't actually the recommended way to do it in production, as it can leak information to the public.

I’m guessing you were distracted after writing the comment ... using PDO, as the rest of the tutorial looks correct, please amend to MySQLi (OOP) and/or create/update an example for PDO.

The reason I searched for PDO connection information was I wanted to know if I can connect to MySQL 8 database using caching_sha2_password now, the manual hasn’t been updated in some time: https://www.php.net/manual/en/ref.pdo-mysql.php and is quoting “When running a PHP version before 7.1.16, or PHP 7.2 before 7.2.4, set MySQL 8 Server’s default password plugin to mysql_native_password”, I’m not sure if this has been fixed now. Would you know if this has been fixed now?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment