Ways of Connecting to MySQL through PHP
Today we will see how to program databases connection in PHP. In order to store or access the data inside a MySQL database, you first need to connect to the MySQL database server and a PHP script.
When developers usually say database, they are referring to MySQL. MySQL’s ability to handle huge volumes of data without breaking .
There are three types of methods in PHP to connect MySQL database:
1.MySQL
2.MySQLi
3.PDO
MySQL
Below PHP script connect to Mysql Database –
$con = mysqli_connect('hostname', 'uesrname', 'password', 'database name'); if (!$con) { echo "Error: " . mysqli_connect_error(); exit(); }
MySQLi
It provides a better set of functions and extensions. It works just like the previous version, but it is safer and faster.
Create a new PHP file(db_connection.php) to check your database connection
function OpenCon() { $dbhost = "localhost"; $dbuser = "root"; $dbpass = "1234"; $db = "example"; $conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s\n". $conn -> error);</p> <p> return $conn;<br ?--> } function CloseCon($conn) { $conn -> close(); }
Create a new PHP file to connect to your database. Name it index.php and add this code in this file.
include 'db_connection.php'; $conn = OpenCon(); echo "Connected Successfully"; CloseCon($conn);
PDO
PHP Data Objects (PDO) extension is a Database Abstraction Layer. It is like an interface for the backend to interact with the MySQL database .
$dsn = "mysql:host=localhost;dbname=mydb"; $user = "user12"; $passwd = "12user"; $pdo = new PDO($dsn, $user, $passwd); $stm = $pdo->query("SELECT * FROM test"); $rows = $stm->fetchAll(PDO::FETCH_NUM); foreach($rows as $row) { printf($row); } In this post, we saw how to connect database in PHP with 3 different types of databases. Hope you like it.