Connecting TO MySQL via PHP

PHP offers two different ways to connect to MySQL server: MySQLi (Improved MySQL) and PDO (PHP Data Objects) extensions.

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

$host = 'mysql-xxxxx-0.cloudclusters.net';
$db   = 'your database name';
$user = 'your database user name';
$pass = 'your password';
$port = "port";
$charset = 'utf8mb4';

$options = [
    \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
    \PDO::ATTR_EMULATE_PREPARES   => false,
];
$dsn = "mysql:host=$host;dbname=$db;charset=$charset;port=$port";
try {
     $pdo = new \PDO($dsn, $user, $pass, $options);
     echo "Connected successfully";
} catch (\PDOException $e) {
     echo "Connection failed: " . $e->getMessage();
}

?>
Copyright © 2021 Cloud Clusters Inc. all right reserved,powered by GitbookRevised on 09/10/2021

results matching ""

    No results matching ""