0
2.0kviews
How to connect to MySQL database using PHP.
1 Answer
0
31views

MySQL Database Connectivity with PHP

  • There are three ways to connect MySQL database using PHP, such as
    • MySQLi (object-oriented)
    • MySQLi (procedural)
    • PDO
  • PDO (PHP Data Objects) will work on 12 different database systems, whereas MySQLi will only work with MySQL databases.
  • So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries. With MySQLi, you will need to rewrite the entire code - queries included.
  • Both are object-oriented, but MySQLi also offers a procedural API.
  • Both support Prepared Statements. Prepared Statements protect from SQL injection, and are very important for web application security.

MySQL Database Connectivity by using MySQLi (object-oriented)

<?php
$servername = "localhost";
    $username = "username";
$password = "password";
    // Create connection
    $conn = new mysqli($servername, $username, $password);
    // Check connection
    if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    } 
    echo "Connected successfully";
    $conn->close();
?>

MySQL Database Connectivity by using MySQLi (procedural)

<?php
$servername = "localhost";
    $username = "username";
$password = "password";
    // Create connection
    $conn = mysqli_connect($servername, $username, $password);
    // Check connection
    if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
mysqli_close($conn);
    ?>

#### **MySQL Database Connectivity by using PDO** ####

    <?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(); }
        $conn = null;
?>
Please log in to add an answer.