Creating An Add-on Domain In cPanel
If you want to create an Add- domain in your cPanel then you have to…
When creating dynamic webpages, connecting a PHP application to a MySQL database is a vital step. PDO (PHP Data Objects) and MySQLi (MySQL Improved Extension) are two well-liked ways that PHP provides for creating this connection.
Let’s explore the two methods:
MySQLi supports both object-oriented and procedural approaches.
<?php
$servername = “localhost”;
$username = “root”;
$password = “”;
$database = “test_db”;
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}
echo “Connected successfully (MySQLi - OOP)”;
?>
<?php
$servername = “localhost”;
$username = “root”;
$password = “”;
$database = “test_db”;
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die(“Connection failed: ” . mysqli_connect_error());
}
echo “Connected successfully (MySQLi - Procedural)”;
?>
PDO is more flexible as it supports multiple databases (MySQL, PostgreSQL, SQLite, etc.), making it a preferred option for larger projects.
<?php
$servername = “localhost”;
$username = “root”;
$password = “”;
$database = “test_db”;
try {
$conn = new PDO(“mysql:host=$servername;dbname=$database”, $username, $password);
// Set PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo “Connected successfully (PDO)”;
} catch(PDOException $e) {
echo “Connection failed: ” . $e->getMessage();
}
?>
This way, you can connect a MySQL database to PHP using MySQLi and PDO. Hope you liked our article. For more informative articles, please visit our KB section regularly.
Learn more tutorials about the PHP Script to Test MySQL Database Connectivity.
Explore more hosting insights, tips and industry updates.
If you want to create an Add- domain in your cPanel then you have to…
In this guide, we will look at how to check the PHP version and settings…
The e-commerce sites can be online via a number of solutions. The site can be…