Connecting PHP to MySQL

MySQL works great with multiple platforms such as Java, C, C++, Python, PHP etc. However, in this series of articles, our focus will be on executing MySQL queries via PHP queries.

Though there are multiple ways of connecting PHP scripts to MySQL, this article focuses on using MySQLi technology. MySQLi provides both object oriented as well as procedural way of connecting to MySQL databases. In this article, we shall see both approaches.

Object Oriented MySQLi

Object oriented MySQLi uses built-in mysqli class to connect to MySQL databases. This object takes three parameters i.e. database name, user name and password. When used in if block the connect_error function of the mysqli object returns true if connection establishment is failed, else it returns false. Let’s have a look at a working example.




Using MySQLi for connecting PHP to MySQL



connect_error) {
    die("Connection not established: " . $connection->connect_error);
} 
echo "Connection established successfully.";
?>



Download the code

To run this code on your machine you will have to change the values for server, username and password and replace it with your own.

Procedural MySQLi

Apart from creating mysqli object, you can also connect PHP scripts with MySQL database via procedural MySQLi approach. This is demonstrated in the following example.




Using MySQLi for connecting PHP to MySQL



connect_error) {
    die("Connection not established: " . $connection->connect_error);
} 
echo "Connection established successfully.";
?>



Download the code

In procedural MySQLi you simply use mysqli_connect function rather than creating object of mysqli to connnect PHP script to MySQL.

<<< PHP Frameworks
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .