Connection to DB

时间:2023-03-09 02:16:35
Connection to DB

Connect to MySQL

PHP5 and later can work with a MySQL database using

  •   MySQLi extension
  •   PDO

PDO will work on 12 different database systems, where as MySQLi will only work with MySQL database.

<!-- MySQLi Object-Oriented -->

<?php

  $servername = "localhost";

  $username = "username";

  $password = "pwd";

  

  //create  connection

  $conn = new mysqli($servername, $username, $password);

  //check connection

  if($conn-> conncet_error){

    die("Connection failed:" .$conn->connect_error);

  }

  echo "Connected successfully";

  $conn->close();

?>

<!-- MySQLi Procedual -->

<?php

  $servername = "localhost";

  $username = "username";

  $password = "pwd";

  //create connection

  $conn = mysqli_connect($servername, $username, $password);

  //check connection

  if(!$conn){

    die("Connection failed:" .mysqli_connect_error());

  }

  echo "Connected successfully";

  mysql_close($conn);

?>

<!-- PDO -->

<?php

  $servername = "localhost";

  $username = "username";

  $password = "pwd";

  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 "Connection successfully";

    $conn = null;

  }

  catch(PDOException $e){

    echo "Connection failed:" .$e->getMessage();

  }

?>