Before working with database you should create connection with database other wise your queries will be not work or fail, if you are using mysql database there are 3 type of connection we can create:
1. Using mysql Database Connection in PHP
2. Using mysqli database connection in php
3. PDO (PHP Data Object)
So Here we are writing code of how to create mysql database connection with PHP PDO.
Here we write simple PDO connection code for use just copy it. You need only change database name, host, username and paswword.
<?php $HostName = 'localhost'; $DataBase = 'test'; $UserName = 'root'; $PassWord = ''; try { $DBH = new PDO("mysql:host=$HostName;dbname=$DataBase", $UserName, $PassWord); $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); } catch(PDOException $e){ echo $e->getMessage; } ?>
// SELECT QUERY USING PHP PDO $STH = $DBH->query('SELECT * from users'); $STH->setFetchMode(PDO::FETCH_ASSOC); while($row = $STH->fetch()) { echo $row['id'] . " "; echo $row['username'] . "<br>"; }
My name is Mukesh Jakhar and I am a Web Application Developer and Software Developer, currently living in Jaipur, India. I have a Master of Computer Application in Computer Science from JNU Jaipur University. I loves to write on technology and programming topics. Apart from this, I love to travel and enjoy the beauty of nature.