The Wayback Machine - https://web.archive.org/web/20240703081647/https://www.geeksforgeeks.org/php-mysql-database-introduction/
Open In App

PHP | MySQL Database Introduction

Last Updated : 08 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

What is MySQL? 
MySQL is an open-source relational database management system (RDBMS). It is the most popular database system used with PHP. MySQL is developed, distributed, and supported by Oracle Corporation.  

  • The data in a MySQL database are stored in tables which consists of columns and rows.
  • MySQL is a database system that runs on a server.
  • MySQL is ideal for both small and large applications.
  • MySQL is very fast, reliable, and easy to use database system.It uses standard SQL
  • MySQL compiles on a number of platforms.

Downloading MySQL Database 
MySQL can be downloaded for free from this link. 

How to connect PHP with MySQL Database? 
PHP 5 and later can work with a MySQL database using:  

  1. MySQLi extension.
  2. PDO (PHP Data Objects).

Difference Between MySQLi and PDO  

  • PDO works on 12 different database systems, whereas MySQLi works only with MySQL databases.
  • Both PDO and MySQLi are object-oriented, but MySQLi also offers a procedural API.
  • If at some point of development phase, the user or the development team wants to change the database then it is easy to that in PDO than MySQLi as PDO supports 12 different database systems.He would have to only change the connection string and a few queries. With MySQLi,he will need to rewrite the entire code including the queries.

There are three ways of working with MySQl and PHP 

  1. MySQLi (object-oriented)
  2. MySQLi (procedural)
  3. PDO
     

Connecting to MySQL database using PHP
There are 3 ways in which we can connect to MySQl from PHP as listed above and described below: 

  • Using MySQLi object-oriented procedure: We can use the MySQLi object-oriented procedure to establish a connection to MySQL database from a PHP script. 

    Syntax: 

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Creating connection
$conn = new mysqli($servername, $username, $password);

// Checking connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
?>

Output: 

Explanation: We can create an instance of the mysqli class providing all the necessary details required to establish the connection such as host, username, password etc. If the instance is created successfully then the connection is successful otherwise there is some error in establishing connection. 
 

  • Using MySQLi procedural procedure : There is also a procedural approach of MySQLi to establish a connection to MySQL database from a PHP script as described below. 

    Syntax: 

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Creating connection
$conn = mysqli_connect($servername, $username, $password);

// Checking connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

Output: 

Explanation: In MySQLi procedural approach instead of creating an instance we can use the mysqli_connect() function available in PHP to establish a connection. This function takes the information as arguments such as host, username , password , database name etc. This function returns MySQL link identifier on successful connection or FALSE when failed to establish a connection. 

  • Using PDO procedure: PDO stands for PHP Data Objects. That is, in this method we connect to the database using data objects in PHP as described below: 

    Syntax: 

<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
    $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
    // setting the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully"; 
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
?>

Output: 

Explanation:The exception class in PDO is used to handle any problems that may occur in our database queries. If an exception is thrown within the try{ } block, the script stops executing and flows directly to the first catch(){ } block. 

                                                                                     Closing A Connection

When we establish a connection to MySQL database from a PHP script , we should also disconnect or close the connection when our work is finished. Here we have described the syntax of closing the connection to a MySQL database in all 3 methods described above. We have assumed that the reference to the connection is stored in $conn variable.

  • Using MySQLi object oriented procedure 
    Syntax 
$conn->close();
  • Using MySQLi procedural procedure 
    Syntax 
mysqli_close($conn);
  • Using PDO procedure 
    Syntax 
$conn = null;

Previous Article
Next Article

Similar Reads

How to Generate Database Dump of MySQL Database in Linux?
We will learn how to Backup and Restore your MySQL Database with Mysqldump query in LINUX. We had always a need that if the production database is corrupted somehow, we should be able to recover it, for recovering we should always keep a backup of the database at particular instances. So, data rollback can be done. First, we will create a Database
2 min read
PHP | MySQL ( Creating Database )
What is a database? Database is a collection of inter-related data which helps in efficient retrieval, insertion and deletion of data from database and organizes the data in the form of tables, views, schemas, reports etc. For Example, university database organizes the data about students, faculty, and admin staff etc. which helps in efficient retr
3 min read
PHP | Inserting into MySQL database
Prerequisites : MySQL introduction, Creating MySQL database INSERT INTO statement is used to insert new rows in a database table. Let's see the syntax how to insert into table, considering database already exists. SYNTAX : INSERT INTO TABLE_NAME (column1, column2, column3, ... columnN) VALUES (value1, value2, value3, ...valueN); Here, column1, colu
4 min read
Create a drop-down list that options fetched from a MySQL database in PHP
In many scenarios, we may need to create a dropdown input that can display all the options consistent with the current state of the database. This form of input is used many times in real life and the following examples may help to understand the same. A set of students who have unique registration numbers.A set of branch names and their branch ids
4 min read
How to retrieve data from MySQL database using PHP ?
There are steps to understand for retrieving the data from the MySQL database. Approach: Create the database, then create the table for data.Enter the rows in the table. You have to connect to the database. Now we understand each and every step as shown below. Example 1: In this. we use PHPMyAdmin for the database handling. Start the server in the
2 min read
How to Update Data in MySQL Database Table Using PHP?
Updating data in a MySQL database table using PHP is a fundamental aspect of web development, particularly in applications where user interactions involve modifying existing records. This guide delves into the process of updating data in a MySQL database table using PHP, covering database connection, SQL queries, error handling, and best practices.
3 min read
How to Upload Multiple Images and Text to MySQL Database in PHP?
In web development, many times we need to handle multiple files at once while uploading and storing into the database. So in this article, we will see how to do this by various approaches to achieve this using PHP and MySQL. Table of Content Storing Images in the File SystemUsing Base64 EncodingApproach 1: Storing Images in the File SystemIn this a
4 min read
How to Insert JSON data into MySQL database using PHP?
To insert JSON data into MySQL database using PHP, use the json_decode function in PHP to convert JSON object into an array that can be inserted into the database. Here, we are going to see how to insert JSON data into MySQL database using PHP through the XAMPP server in a step-by-step way. JSON Structure:[{ "data1": "value1", "data2": "value2", .
3 min read
MySQL | Common MySQL Queries
MySQL server is a open-source relational database management system which is a major support for web based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. Even all social networking websites mainly Facebook, Twitter, and Google depends on MySQL dat
9 min read
Functions in MySQL | Numeric, String and Date Time Functions in MySQL
MySQL functions are powerful tools that help in performing complex calculations and data manipulation with ease. The functions in MySQL can edit rows and tables, alter strings, and help you manage organized and easy-to-navigate databases. A function is a special type of predefined command set that performs some operation and returns a value. Functi
3 min read
three90RightbarBannerImg