Tuesday, 10 July 2018

PHP Connect to MySQL Main Tips

PHP Connect to MySQL Main Tips

  • Two main methods to work with the MySQL database: MySQLi extension and PDO (PHP Data Objects).
  • Both methods have their advantages.
  • This post demonstrates three different examples how to connect to a database: MySQLi (object-oriented)MySQLi (procedural) and PDO.

MySQLi Installation

MySQLi extension usually installs automatically with PHP5 MySQL package. This works on Linux and Windows operating systems.
For installation details, go to: http://php.net/manual/en/mysqli.installation.php

PDO Installation

For installation details, go to: http://php.net/manual/en/pdo.installation.php

Open a Connection to Database

Before starting to modify the MySQL database, we need to establish the connection with a server.

This example shows how to make a connection using MySQLi Object-Oriented method.

Example (MySQLi Object-Oriented)

  1. <?php
  2. $servername = "localhost";
  3. $username = "name_of_the_user";
  4. $password = "users_password";
  5. // Create connection
  6. $conn = new mysqli($servername, $username, $password);
  7. // Check connection
  8. if ($conn->connect_error)
  9. {
  10. die("Failed to connect: " . $conn->connect_error);
  11. }
  12. echo "Connected successfully";
  13. ?>
This example displays different MySQLi method.

Example (MySQLi Procedural)

  1. <?php
  2. $servername = "localhost";
  3. $username = "name_of_the_user";
  4. $password = "users_password";
  5. // Create connection
  6. $conn = mysqli_connect($servername, $username, $password);
  7. // Check connection
  8. if (!$conn)
  9. {
  10. die("Failed to connect: " . mysqli_connect_error());
  11. }
  12. echo "Connected successfully";
  13. ?>
There is a database (myDatabase) specified in the PDO example below. This is because PDO requires a database for the connection. Examples above do not require a database name for connecting to the server (it will be needed when accessing the database itself).

Example (PDO)

  1. <?php
  2. $servername = "localhost";
  3. $username = "name_of_the_user";
  4. $password = "users_password";
  5. try
  6. {
  7. $conn = new PDO("mysql:host=$servername; dbname=myDatabase", $username, $password);
  8. $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
  9. echo "Connected successfully";
  10. }
  11. catch(PDOException $e)
  12. {
  13. echo "Failed to connect: " . $e->getMessage();
  14. }
  15. ?>
Note: One of the benefit of using PDO is the “try-catch” blocks. It can catch any errors in the “try” block and execute error handling code in “catch” block.

Close the Connection

The connection closes automatically when the script stops running. If you want to close the connection earlier, use the following syntax:

Example (MySQLi Object-Oriented)

  1. $conn->close();

Example (MySQLi Procedural)

  1. mysqli_close($conn);

Example (PDO)

  1. $conn = null;

0 comments:

Post a Comment