Database connection in PHP
You need to database connection when you get or fetch data into the MySQl table. In PHP programming language when you access MySQL table or Database then you must need database connect.
In this tutorial I will help you How to connect database in you PHP web application. How to connect database using MySQL, How to connect database using MySQLi and how to connect database using PDO in PHP?
You know MySQL is the most popular database connection system in the PHP web application. The databases are helpful for storing all information with categorically of project and applications.
Database connection using MySQL in PHP
It is the easy way to connect database in PHP. This connection was used before PHP 5 but now later Mysqli useing for database connection. There are many different type of database connection I will show you in this tutorial. Example code of MySQL connection in PHP.
@mysql_connect($servername, $username, $password);
@mysql_select_db($dbname);
Example:
@mysql_connect("localhost","root",""); @mysql_select_db("Database Name"); Or Try It @mysql_connect("localhost","root","") or die("Host Is Not Connect !!"); @mysql_select_db("Database Name") or die("Database Is Not Connect !!");
Database connection using MySQLi in PHP
It is so helpful tutorial and quick connection of database in PHP using MySQLi. Follow the code-
$ servername="localhost"; $ username="user Name"; $ password="password"; $ dbname="db name"; $db_con = mysqli_connect($servername, $username, $password, $dbname);
Example
$db_con=mysqli_connect("localhost","root","","Database Name"); Or Try It $db_con=mysqli_connect("localhost","root","","shop") or die("Database Is Not Connect, Please Chack Again");
Database connection using PDO in PHP
The PDO has an exception class that handle any issues that it may cause in a database query in PHP.
Example:
$your_servername = "localhost"; $server_username = "username"; $server_password = "password"; try { $db_con = new PDO("mysql:host=$servername;dbname=myDB", $username, $password); $db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Database Connected Successful"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); }