• Thu, Nov 2024

How To Connect PHP To MYSQL Database

How To Connect PHP To MYSQL Database

How To Connect PHP To MYSQL Database

PHP Connect to MySQL

There are 2 type of connect

   1) MySQLi   
   2) PDO

Which one I Use MySQLi or PDO?

If you need a short answer, it's "Whatever you want."

Both MySQLi and PDO have their benefits:

PDO supports 12 other database systems, but MySQLi is limited to MySQL databases.

Prepared Statements protect from SQL injection, and are very important for web application security.

For Linux and Windows: The MySQLi extension is automatically installed in most cases, when php5 mysql package is installed.

For installation details, go to: http://php.net/manual/en/mysqli.installation.php

PDO Installation

For installation details, go to: http://php.net/manual/en/pdo.installation.php


connect to the server:

Example (MySQLi)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

$conn = mysqli_connect($servername, $username, $password);

if (!$conn) {
 die("Connection failed: " . mysqli_connect_error());
}
echo "Connection success";
?>


Example (PDO)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
 $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
 
 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 echo "Connection Sucess";
} catch(PDOException $e) {
 echo "Connection failed: " . $e->getMessage();
}
?>


Close connection (MySQLi)

$conn->close();

Close connection (PDO)

mysqli_close($conn); 

 

Download Full Code HERE 

Download Fome Here