Open In App

How to make a connection with MySQL server using PHP ?

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

MySQL is a widely used database management system that may be used to power a wide range of projects. One of its main selling features is its capacity to manage large amounts of data without breaking a sweat. There are two approaches that can be used to connect MySQL and PHP code, which are mentioned below.

Let’s get to know both of these options a bit more.

A Database Abstraction Layer is the PHP Data Objects (PDO) extension. It functions as a user interface for the backend to interact with the MySQL database and make changes without altering the PHP code. It also allows you to deal with numerous databases at the same time. The main benefit of using PDO is that it keeps your code simple and portable.

MySQLi is a connector function that connects the PHP app’s backend to the MySQL database. It performs in the same way as the previous version, but it is safer and faster, with a more comprehensive collection of functions and extensions. With PHP 5.0.0, MySQLi was launched, and the drivers were installed with PHP 5.3.0. The API was created to work with MySQL versions 4.1.13 and higher.

Connect with MySQL: Before one can access data in the MySQL database, one needs to be able to connect to the server. Use the mysqli_connect() function according to your connecting way to establish a database connection. This function returns a database connection pointer also known as a database handle. This handle will be utilized later in the code. Remember to add your database credentials after you get the handle.

1. Connection via PDO – A database is also supplied in the PDO example below (“geeksDatabase”). To connect to a database, PDO requires a valid database else an exception is thrown.

PHP




<?php
  
$servername = "localhost";
$username = "user";
$password = "123456";
$dbName = "geeksDatabase";
  
try {
  
    // Creating the connection
    $conn = new PDO("mysql:host=$servername;dbname=$dbName"
                    $username, $password);
    
    // Setting the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connection established successfully...";
    
    // To close the connection
    $conn = null;
  
// If connection fails 
catch(PDOException $e) {
  
      // Throws the error message 
    echo "Connection failed: " . $e->getMessage();
}
  
?>


Output:

Connection established successfully...

2. Connection via MySQLi – 

PHP




<?php
  
$servername = "localhost";
$username = "user";
$password = "123456";
$dbName = "geeksDatabase";
  
// Creating connection
$conn = mysqli_connect($servername
         $username, $password, $dbName);
  
// Checking connection
if (!$conn) {
  
      // If connecting fails
    die("Connection failed: " . mysqli_connect_error());
}
  
echo "Connection established successfully...";
  
// Close the connection  
mysqli_close($conn);
  
?>


Output:

Connection established successfully...


Previous Article
Next Article

Similar Reads

Laravel | MySQL Database Connection
The database is an important element in any application. Laravel by default provides the support of MySQL. MySQL is a well known, open-source RDBMS (Relational Database Management System). Process for Connecting to the Database: Step 1: First we have to create a database. So, we will start Apache and MySQL server form XAMPP Control Panel. Step 2: O
3 min read
Load CSV Data into MySQL Server Using PHP
In this article, we are going to store data present in CSV file into MySQL database using PHP in XAMPP server and display the data on web browser. Comma Separated Value (CSV) is a text file containing data contents. It facilitates the storage of data in a table like structure. CSV files are stored with a CSV extension. A CSV file can be created wit
3 min read
How to wait for MongoDB connection to be made before creating HTTP server in Node.js?
Connecting your server to is a database a very crucial task in back-end development as the database is the location where the user-provided data will be stored until further action is taken. If we fail to connect to the database before creating the server, whatever data is being processed by the server will not get stored in the database. So, as a
3 min read
How to make a Todo App using PHP & MySQL ?
To create a Todo App using PHP and MySQL, you'll first need to set up a MySQL database to store the tasks. Then, use PHP to create a web interface where users can add, edit, and delete tasks. PHP will handle the backend logic, such as connecting to the database and performing CRUD operations. Finally, use HTML and CSS to design the frontend interfa
4 min read
PHP Database connection
The collection of related data is called a database. XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for website development. Requirements: XAMPP web server procedure: Start XAMPP server by starting Apache and MySQL. Write PHP script for connecting to XAMPP. Run it in the local browse
2 min read
How to Connect to Mysql Server Using VS Code and Fix errors?
MySQL is a relational database management system based on SQL-Structured Query Language used for accessing and managing records in a database. It can be easily connected with programming languages such as Python, Java, and PHP to serve various purposes that require CRUD ( Create,Read,Update,Delete) operations. MySQL is based on a client – server ar
4 min read
Microsoft Azure - Using Flexible Server in Azure Database for MySQL
Pre-requisite: Azure VM Azure Database for MySQL is a PaaS implementation of MySQL in the Azure cloud. It provides high availability at no extra charge, as well as scalability as needed, automatic backups, and point-in-time restores. Connection security is provided by the server, which enforces firewall restrictions and, optionally, requires SSL co
2 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
How to detect the Internet connection is offline or not using JavaScript?
In some cases, it is necessary to determine whether the browser is online or offline before performing a required task. Many developers use AJAX to determine the connection status of the browser (online or offline) by sending a request to the server. However, this is not a good method for determining the state of the browser because it requires ban
1 min read
How to accept all pending connection requests on LinkedIn using JavaScript ?
Many times we get a lot of connection requests over LinkedIn, and we want to accept all of them but for that, we have to click the accept button for each connection request. With the help of the following way, we can accept all of them at once using JavaScript helping us to save our time and effort. Approach: Make a variable connection that points
2 min read