06- MySQL Connect

0
53

MySQL Connect

Since PHP 5 or later can now work with MySQL database the MySQLi or PDO_MySQL extension should be used. The functions include:

  • Mysqli_connect()
  • PDO::_construct()

Which is better to use, MySQLi or PDO?

Well the answer depends on you, but both MySQLi and PDO have their advantages:

The MySQLi can only work with MySQL databases unlike to the PDO will work on 12 different Database systems.

Meaning if you want to switch your project to use, the PDO makes the process easy, because you are no longer required to rewrite all the codes but you have only to change the connection string and few queries unlike to MySQLi, you have to recode or rewrite the entire code including the queries.

PDO and MySQLi are Object-oriented, only MySQLi offers a procedural API.

 

Here are the examples of MySQL in Both MySQLi and PDO

Reminder:

Before connecting to MySQL and access the data, make sure that the server is open.

Example of MySQLi (Object-Oriented):

  1. <?php
  2. $server = "localhost";
  3. $username = "root";
  4. $password = "";
  5.  
  6. // Create connection
  7. $conn = new mysqli($server, $username, $password);
  8.  
  9. // Check connection
  10. if ($conn->connect_error) {
  11. die("Connecting to database failed: " . $conn->connect_error);
  12. }
  13. echo "Connected successfully";
  14. ?>

Example of Closing the MySQLi (Object-Oriented):

  1. $conn->close();

 

Example of MySQLi (Procedural):

  1. <?php
  2. $server = "localhost";
  3. $username = "root";
  4. $password = "";
  5.  
  6. // Create connection
  7. $conn = mysqli_connect($server, $username, $password);
  8.  
  9. // Check connection
  10. if (!$conn) {
  11. die("Connecting to database failed: " . mysqli_connect_error());
  12. }
  13. echo "Connected successfully";
  14. ?>

Example of Closing the MySQLi (Procedural):

Example PDO:

  1. <?php
  2. $server = "localhost";
  3. $username = "root";
  4. $password = "";
  5.  
  6. try {
  7. $conn = new PDO("mysql:host=$server;dbname=test", $username, $password);
  8. // set the PDO error mode to exception
  9. $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  10. echo "Connected successfully";
  11. }
  12. catch(PDOException $e)
  13. {
  14. echo "Connection failed: " . $e->getMessage();
  15. }
  16. ?>

 

An example of Closing the PDO:

  1. $conn = null;

Go Back to our Previous lesson entitled “MySQL Database

Facebook Comments
(Visited 43 times, 2 visits today)

LEAVE A REPLY

Please enter your comment!
Please enter your name here