PHP Connect to MySQL
mysql_connect is used to conect php with database.
mysql_connect
(PHP 4, PHP 5)
mysql_connect — Open a connection to a MySQL Server
Since PHP 5.5, mysql_connect() extension is deprecated. Now it is recommended to use one of the 2 alternatives.
mysqli_connect()
PDO::__construct()
Syntax
mysql_connect("server_name","username","password")
Example (mysql_connect)
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysql_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " .mysql_error());
}
echo "Connected successfully";
?>
PHP 5 and later can work with a MySQL database using:
MySQLi extension (the "i" stands for improved)
PDO (PHP Data Objects)
Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in 2012.
| MySQLi |
PDO |
| MySQLi will only work with MySQL databases |
PDO will work on 12 different database systems |
| With MySQLi, you will need to rewrite the entire code - queries included |
if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries |
| MySQLi also offers a procedural API. |
PDO does not offers procedural API |
Both support Prepared Statements. Prepared Statements protect from SQL injection, and are very important for web application security.
mysqli_connect()
PHP mysqli_connect() function is used to connect with MySQL database. It returns resource if connection is established or null.
There are Two ways in mysqli
MySQLi (object-oriented)
MySQLi (procedural)
MySQLi Procedural
Syntax
mysqli_connect("server_name","username","password")
Example(MySQLi Procedural)
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$conn = mysqli_connect($host, $user, $pass); if(! $conn )
{
die('Could not connect: ' . mysqli_error());
} echo 'Connected successfully';
mysqli_close($conn);
?>
Output:
Connected successfully
MySQLi Object-Oriented
Before we can access data in the MySQL database, we need to be able to connect to the server:
Example(MySQLi Object-Oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Previous
Next