pdo connection php code example
Example 1: php mysql pdo connection
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Example 2: php pdo connection
$host = "localhost";//Ip of database, in this case my host machine
$user = "root"; //Username to use
$pass = "qwerty";//Password for that user
$dbname = "DB";//Name of the database
try {
$connection = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e)
{
echo $e->getMessage();
}
Example 3: pdo db connection
<?php
$pdo = new PDO('mysql:host=localhost;dbname=databasename', 'username', 'password');
?>
Example 4: how to connect pdo php database
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Example 5: pdo connexion
public static function connexionBDD()
{
$base = null;
try {
$base = new PDO('mysql:host=' . MYSQL_HOSTNAME . '; dbname=' . MYSQL_DATABASE . '', MYSQL_USERNAME, MYSQL_PASSWORD);
} catch (exception $e) {
die('Erreur ' . $e->getMessage());
}
return $base;
}
Example 6: PDO connect
<?php
$db = new PDO('mysql:host=myhost;dbname=mydb', 'login', 'password');