Interfacing with the database in PHP: Here, we will figure out how to associate with the different databases like MySQL, Postgres, SQLite, and so on?
Here, we are utilizing PDO (PHP Data Objects) to make a MySQL association. We at that point check if there are any blunders. On the off chance that there are none, we print “associated Successfully” or disaster will be imminent, we print “association fizzled” trailed by the blunder tossed by PDO.
1) Connecting with MySQL in PHP
<?php
$host = "localhost";
$uname = "username";
$pw = "password";
$db = "newDB";
try {
$conn = new PDO("mysql:host=$host;dbname=$db", $uname, $pw);
// set error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
2) Connecting with Postgres in PHP
<?php
$host = "localhost";
$uname = "username";
$pw = "password";
$db = "newDB";
$dbcon = pg_connect("host=$host port=5432 dbname=$db user=$uname password=$pw");
?>
Here, we are utilizing the pg_connect() technique to associate with a Postgres database. We can decide to either characterize the database subtleties in variables or inline straightforwardly.
3) Connecting with the SQLite database in PHP
<?php
class MyDB extends SQLite3 {
function __construct() {
$this->open('example.db');
}
}
?>
Here, we are making another Class (myDB) which reaches out to the SQLite3 augmentation. __construct function is utilized to make an array that holds the example.db SQLite database.