ITSourceCode.com

We Exist to Provide 100% Free Source Code and Tutorials

Custom Search

06-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 is 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 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 re code 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. ?>

 

Example of Closing the PDO:

  1. $conn = null;
Facebook Comments

Check Your Domain Ranking

Leave a Reply

Your email address will not be published. Required fields are marked *

ITSourceCode.com © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!