Connecting to MySQL Server using PHP

Using PHP to connect to MySQL Server is also possible. Below, we give several examples of code.

1. MySQLi Object-oriented

<?php
$servername = "host";
$username = "username";
$password = "password";
$dbname   = "databasename";
$dbServerPort = "port";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname, $dbServerPort,);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
?>

2. MySQLi Procedural

<?php
$servername = "host";
$username = "username";
$password = "password";
$dbname   = "databasename";
$dbServerPort = "port";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname, $dbServerPort,);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

3. PDO(PHP Data Objects)

<?php
$servername = "host";
$username = "username";
$password = "password";
$dbname   = "databasename";
$dbServerPort = "port";

try {
    $conn = new PDO("mysql:host=$servername, $username, $password, $dbname, $dbServerPort,);
    // 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();
    }
?>
Copyright © 2019 Cloud Clusters Inc.Revised on 07/23/2020

results matching ""

    No results matching ""