Practical Web Programming

Thursday, January 10, 2008

Accessing MySQL Database Using PHP

Accessing MySQL database is one of the best uses of PHP. In fact, the PHP's support for MySQL has been included since the first public usable version of the language. PHP and MySQL are like blood-brother, as some programmers say.

This PHP source code shows how to access a MySQL database and display the result. This example assumes the you're running PHP and MySQL in your local PC. If you don't have PHP and MySQL, you can download the XAMPP installer. XAMPP is an easy to install Apache distribution containing MySQL, PHP and Perl. I use this a lot.

In your MySQL, create a database named "company" and a table named "employee". See the SQL DDL below.
create table employee(
id smallint(5),
name varchar(35),
email varchar(35));


Connect to database, where;

"localhost" is you database server
"un" is the username defined in your database
"pw" is the password for the username

$db = mysql_connect("localhost", "un", "pw") or
die("Cannot connect to the database");


Select the database

mysql_select_db("company");


Set up the SQL statement and query the employee table

$result = mysql_query("SELECT id, name, email FROM employee") or
die(mysql_error());


Loop & display the resultset

while($rows = mysql_fetch_assoc($result))
{
echo "<b>ID</b>".$rows["id"]."<br>";
echo "<b>Name</b>".$rows["name"]."<br>";
echo "<b>Email</b>".$rows["email"]."<br><br>";
}


Summing it all up

<?php
$db = mysql_connect("localhost", "un", "pw") or
die("Cannot connect to the database");
mysql_select_db("company");

$result = mysql_query("SELECT id, name, email FROM employee") or
die(mysql_error());

while($rows = mysql_fetch_assoc($result))
{
echo "<b>ID</b>".$rows["id"]."<br>";
echo "<b>Name</b>".$rows["name"]."<br>";
echo "<b>Email</b>".$rows["email"]."<br><br>";
}
?>


Note: You can use print instead of echo.

0 comments:

Recent Post