0
How to connect to MySQL database using PHP.

Mumbai University > information technology > sem 4> Web Programming

Marks: 10M

Year : Dec16

0  upvotes
0

MySQL Examples in Both MySQLi and PDO Syntax

In this, and in the following chapters we demonstrate three ways of working with PHP and MySQL:

  1. MySQLi (object-oriented)

  2. MySQLi (procedural)

  3. PDO

Open a Connection to MySQL

Before we can access data in the MySQL database, we need to be able to connect to the server:

Example (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-\gtconnect_error);
    } 
    echo "Connected successfully";
    ?\gt

**Example (MySQLi Procedural)**

    \lt?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";
    ?\gt

**Example (PDO)**


    \lt?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-\gtsetAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "Connected successfully"; 
        }
    catch(PDOException $e)
    {
    echo "Connection failed: " . $e-\gtgetMessage();
        }
    ?\gt


**Close the Connection**

The connection will be closed automatically when the script ends. To close the connection before, use the following:

**Example (MySQLi Object-Oriented)**


    $conn->close();

Example (MySQLi Procedural)

mysqli_close($conn);

**Example (PDO)**

    $conn = null;
0  upvotes
Please log in to add an answer.

Next up

Read More Questions

If you are looking for answer to specific questions, you can search them here. We'll find the best answer for you.

Search

Study Full Subject

If you are looking for good study material, you can checkout our subjects. Hundreds of important topics are covered in them.

Know More