Connect to MySQL using PHP and fetch / retrieve data from the database
We have reached the final installment of the article where we are going to fetch / retrieve data from the MySQL database using PHP code.
Here is the code:
[php]
<?php
$db_username = “root”;
$db_password = “”;
$db_hostname = “localhost”;
//connection to the database
$db_resource = mysql_connect($db_hostname, $db_username, $db_password)
or die(“Unable to connect to MySQL”);
echo “Connected to MySQL<br>”;
//select a database
$db_select = mysql_select_db(“bittu”,$db_resource)
or die(“Could not select database”);
//execute the SQL query and return records
$result = mysql_query(“SELECT uid, firstname,lastname,email, created_time,active FROM users”);
//fetch data from the database
while ($row = mysql_fetch_array($result)) {
echo “UID:”.$row{‘uid’}.” First Name:”.$row{‘firstname’}.” Last Name: “. $row{‘lastname’}.” Email: “.$row{’email’}.” Created Time:”.$row{‘created_time’}.” Active: “.$row{‘active’}. “<br>”;
}
//close the connection
mysql_close($db_resource);
?>
[/php]
Running this script on browser will output the following:
Connected to MySQL
UID:1 First Name:Bittu Last Name: Sharma Email: bsharma@xyz.com Created Time:2014-08-21 18:22:51 Active: 1
UID:2 First Name:Kamalika Last Name: Roy Email: kroy@abcd.com Created Time:2014-08-21 18:22:52 Active: 1
UID:3 First Name:Bittu Last Name: Sharma Email: bsharma@xyz.com Created Time:2014-08-21 18:22:53 Active: 1
So, that was all about connecting to MySQL and fetching / retrieving data using PHP. Hope you liked it.
Leave a Reply