database connection in php pdo 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);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Example 2: database connection in php pdo
<?php
class database{
private $host = "localhost";
private $db_name = "php_basic";
private $username = "root";
private $password = "";
private $conn;
function connect_pdo(){
try{
$this->conn = new PDO("mysql:host=".$this->host.";dbname=".$this->db_name, $this->username, $this->password);
return $this->conn;
}
catch(PDOException $ex){
echo "Connection Error -->> ",$ex->getMessage();
echo "<br>Error Code -->> ",$ex->getCode();
echo "<br>Error occur in File -->> ",$ex->getFile();
echo "<br>Error occur on Line no -->> ",$ex->getLine();
$this->conn = null;
}
}
}
?>
//how to use
<?php
include 'connect_db.php';
$database=new database();
$db = $database->connect_pdo();
?>
Example 3: pdo db connection
<?php
$pdo = new PDO('mysql:host=localhost;dbname=databasename', 'username', 'password');
?>
Example 4: connect php to mysql pdo
<?php
$pdo = new PDO('mysql:host=localhost;
dbname=the_name_of_your_databe,
'username',
'password'');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
?>