Many dynamic website are created by PHP with MySQL. So this post helps for the beginners to connect the database with PHP. You must establish the connection to get, post, update or delete data from the database.
There are two ways to connect the MySQL database with PHP.
- MySQLi
- PHP Data Object (PDO)
Let’s see the codes below,
MySQLi
Syntax: mysql_connect(hostname, username, password, dtabasename);
<?php
define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'dbname');
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
PHP Data Object (PDO)
Syntax: new PDO("mysql:host=hostname;dbname="dtabasename,username, password);
<?php
// DB credentials.
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASS','');
define('DB_NAME','dbname');
// Establish database connection.
try
{
$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER, DB_PASS);
echo "Connected successfully.";
}
catch (PDOException $e)
{
exit("Error: " . $e->getMessage());
}
?>
Popular Posts
- Show / Hide div based on dropdown selected using jQuery
- Autosuggestion Select Box using HTML5 Datalist, PHP and MySQL with Example
- Custom Authentication Login And Registration Using Laravel 8
- Infinite Scrolling on PHP website using jQuery and Ajax with example
- Google Login or Sign In with Angular Application
- How to Convert MySQL Data to JSON using PHP
- How to change date format in PHP?
- Image Lazy loading Using Slick Slider
- Slick Slider Basic With Example
- php in_array check for multiple values
- Adaptive Height In Slick Slider
- Slick Slider Center Mode With Example
Total Views: 1,860