- 5 years ago
- Zaid Bin Khalid
- 6,759 Views
-
6
In this tutorial, I will try to explain to you how to connect with the MySQL database.
Why do we need to connect with the database? The answer is very simple to perform any operations into the database first, we need to connect with the MySQL database server. So, the PHP offers two unique approaches to connect with MySQL server are MySQLi the advanced method of MySQL, and PDO a PHP Data Objects augmentations.
Difference between PDO & MySqli connection.
The PDO statement is more versatile and supports many databases. While the MySQLi extension only for MySQL database.
The MySQLi is more speedy and provides more facilities then the PDO statement when you are using an MYSQL database. So, It is better to use MySQLi statement over the PDO.
Connection with the help of PHP
PHP is a very famous and powerful language and used in many famous web projects. PHP allows you to connect with the MySQL database with the help of PDO and MySqli statements. In MySQLi you can connect with the database in two ways. Both statements with examples are listed below.
MySQLi, Object-Oriented.
<?php
$mysqli = new mysqli("hostname", "database-username", "database-password", "database");
?>
MySQLi, Procedural.
<?php
$link = mysqli_connect("hostname", "database-username", "database-password", "database");
?>
PHP Data Objects (PDO).
<?php
$db = new PDO("mysql:host=hostname;dbname=database", "database-username", "database-password");
?>
In the above example, the hostname represents the server hostname of your DB normally it is the localhost or the IP address. The user name and the password are the DB credentials. Whenever you create a database that has must these things.
<?php
$link = mysqli_connect("localhost", "root", "", "YOUR-DB-NAME");
//Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}else
// Print host information
echo "Connect Successfully. Host info: " . mysqli_get_host_info($link);
?>
The default username for the MySQL database server is a root. You can create many users for a single DB with different rights or privileges. After connecting to the DB you can close the connection with the help of PHP below code is the simple example.
The complete code will look like below where the connection is created and after creation connection is closed.
<?php
$link = mysqli_connect("localhost", "root", "", "YOUR-DB-NAME");
//Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}else
// Print host information
echo "Connect Successfully. Host info: " . mysqli_get_host_info($link);
mysqli_close($link);
?>
- 5 years ago
- Zaid Bin Khalid
- 6,759 Views
-
6