How to connect various databases using PHP?

Learn, how to connect with the various databases like MySQL, postgres, SQLite, etc?
Submitted by Bhanu Sharma, on September 19, 2019 [Last updated : March 13, 2023]

Connect to MySQL Database Using 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();
}
?> 

Here, we are using PDO (PHP Data Objects) to create a MySQL connection. We then check if there are any errors. If there are none, we print "connected Successfully" or else, we print "connection failed" followed by the error thrown by PDO.

Connect to postgres Database Using 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 using pg_connect() method to connect to a postgres database. We can choose to either define the database details in variables or inline directly.

Connect to SQLite Database Using PHP

<?php
   class MyDB extends SQLite3 {
      function __construct() {
         $this->open('example.db');
      }
   }   
?>

Here, we are creating a new Class (myDB) which extends to the SQLite3 extension. __construct function is used to create an array that holds the example.db SQLite database.

PHP Database Programs »



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.