Question: How to connect to MySQL database using PHP.
0

Subject: Internet Programming

Topic: Server Side Programming: PHP

Difficulty: High

ADD COMMENTlink
modified 14 months ago  • written 14 months ago by gravatar for Binita Mayekar Binita Mayekar40
0

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;
?>
ADD COMMENTlink
modified 14 months ago  • written 14 months ago by gravatar for Binita Mayekar Binita Mayekar40
Please log in to add an answer.