Answers for "db connection class in php using pdo"

PHP
1

pdo connection php

<?php
$db = "mysql:host=localhost;dbname=pdolearn";
$user = "root";
$password = "";

$pdo = new PDO($db, $user, $password);

// $stmt = "SELECT * FROM countries";   //for mySQL
$stmt = $pdo->query("SELECT * from countries");

// while($row = mysqli_fetch_assoc($stmt))  //for mysql
while ($row = $stmt->fetch())
{
    echo    "<pre>";

    print_r($row);
}
Posted by: Guest on October-04-2021
1

database connection in php pdo

<?php
class database{
  private $host = "localhost";
  private $db_name = "php_basic";
  private $username = "root";
  private $password = "";
  private $conn;

  // connect database using PDO
  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; // close connection in PDO
    }
  }
}
?>
  
//how to use 
<?php
include 'connect_db.php';
$database=new database();
$db = $database->connect_pdo();
?>
Posted by: Guest on May-29-2021

Browse Popular Code Answers by Language