Each website and web application we have to need connect with a database . in this tutorials we learn How to connect a MYSQL PDO database in php . We have many way to connect a mysql database in php .
First we have create a dbmodel Class . and define other parameter like dbhost , dbusername , dbpassword , dbname .
create connection string in construct function .
<?php
class dbmodel{
private $dbHost = "localhost";
private $dbUsername = "root";
private $dbPassword = "demo";
private $dbName = "demo";
public function __construct()
{
try {
$conn = new PDO("mysql:host=".$this->dbHost.";dbname=".$this->dbName, $this->dbUsername, $this->dbPassword);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db = $conn;
//echo "Connected successfully<br />";
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
}
}
?>