Google trends Public Holidays Coupon Code Code Compiler

Connecting to MySQL Database

Dec 25, 2018

Summary: in this tutorial, we will show you how to connect to MySQL database server using PDO object.

Before connecting to a MySQL database, you have to specify the following information:

  • MySQL data source name or DSN :  specifies the address of the MySQL database server. You can use IP address or server name e.g.,  or  localhost
  • MySQL database name: indicates the name of the database that you want to connect to.
  • Username and password: specify username and password of the MySQL’s user that you use to connect to the MySQL database server. The account must have sufficient privileges to access the database specified above.
    We will use:
  • The local MySQL database server so the DSN is localhost .
  • The classicmodels as the sample database.
  • The root account with a blank password, just for the sake of demonstration.

Connecting To MySQL Steps

First to make it convenient, we will create a new PHP file for database configuration named  config.php that holds all configured parameters:

$hostname = 'localhost';
$dbname = 'significant';
$username = 'root';
$password = '';

Second, we create a new PHP file named phpmysqlconnect.php :

require_once 'config.php';

try {
     $c PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
    echo "Connected to $dbname at $hostname successfully.";
} catch (PDOException $pe) {
    die("Could not connect to the database $dbname :" . $pe->getMessage());

How the script works.
  • We included the  config.php file into the script by using the  require_once  function.
  • Inside the try block, we created a new PDO object with three arguments: connection string, username, and password. The connection string is composed of  $hostname and $dbname  variables in the  config.php file.
  • If the connection to the MySQL database established successfully, we displayed a success message. If there was any errors or exceptions, PHP issued a PDOException  that contains the detailed error message. We call the getMesage()  method of the PDOException object to get the detailed message for displaying.
Third, let’s test the script from the web browser.

It works as expected. We’ve successfully connected to the MySQL server.

Let’s try to change something in the code to make the script display an error message. If you set the  $username variable to blank, you will get the following error message:
The error message says that:

Access denied for user ''@'localhost' to database 'significant'

Because we don’t have any blank user in the classicmodels database.
When the script ends, PHP automatically closes the connection to the MySQL database server. If you want to close the database connection explicitly, you need to set the PDO object to null 

Copyright 2024. All rights are reserved