The connection file is a base file to connect the database using PDO. PDO provides an easy way to create a connection between the page to the database. You can connect many databases using PHP PDO.
Creating a connection using PDO :-
The PDO connection depends on server connection details. If your server details are correct then it will be connected successfully or if your server details are wrong then it will not be connected. You have to provide the correct host, username, database, and password.
Let's create a PDO connection:-
<?php
ob_start(); session_start();
$databaseHost='localhost';
$databaseUser='root';
$databasePassword='';
$databaseName='test';
try {
$conn = new PDO("mysql:host=".$databaseHost.";dbname=".$databaseName, $databaseUser, $databasePassword);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo 'PDO Connected Successfully';
} catch(PDOException $error) {
//echo "Something went wrong " . $error->getMessage();
}
?>
Set server connection details in variables. Make sure all details are correct.
Let's fetch and display data rows using PHP PDO and MySQL database. We know about fetch and display in HTML table using PHP MySQLi. Here, we will fetch and display data from the database in PHP PDO.
First of all, create a database table -
Open your PHPMyAdmin and create a database.
Let's say database name test
Now, create a table inside the test database with the name products.
CREATE TABLE `products` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`title` varchar(255) DEFAULT NULL,
`price` double NOT NULL
);
Insert some values by query below.
INSERT INTO `products` (`id`, `title`, `price`) VALUES
(1, 'Mobile Phone Xyz', 15000),
(2, 'Laptop 5i', 72000),
(3, 'Tablet 8 GB ', 26999);
We already created a connection between the HTML page to MySQL database using PHP PDO.
Save in config.php or you can save it as a pdo-config.php file.
Create another PHP file index.php and include that pdo-config.php file at the top of the index page.
First of all, select data rows from the database using the Select query.
Use PDO connection variable to provide connection authority to page.
Fetch all the data and display it in an HTML table using a while loop.
index.php
<?php
require_once('pdo-config.php');
$stmt = $conn->query('SELECT * FROM products ORDER BY id DESC');
$rows=$stmt->fetchAll();
?>
<table width='30%' border=1>
<td>Product Name</td>
<td>Product Price </td>
</tr>
<?php
foreach($rows as $row) {
echo "<tr>";
echo "<td>".$row['title']."</td>";
echo "<td>".$row['price']."</td>";
}
?>
</table>
We created a PDO connection successfully.