PHP MySQL


PHP Tutorial > MySQL

Here we give an example of the PHP code that will read data out of a MySQL database and present it in a nice tabular format in HTML.

Assuming we have the following MySQL table:

Table Employee
NameSalary
Lisa40000
Alice45000
Janine60000

The PHP code needed is as follows (assuming the MySQL Server sits in localhost and has a userid = 'cat' and a password of 'dog', the database name is 'myinfo') :

$link = @mysql_pconnect("localhost","cat","dog") or exit();
mysql_select_db("myinfo") or exit();

print "<p>Employee Information";
print "<p><table border=1><tr><td>Employee Name</td><td>Salary
Amount</td></tr>";

$result = mysql_query("select name, salary from Employee");

while ($row=mysql_fetch_row($result))
{
  print "<tr><td>" . $row[0] . "</td><td>" . $row[1] . "</td></tr>";
}

print "</table>";

Output is

Employee Information

Employee NameSalary Amount
Lisa40000
Alice45000
Janine60000

Below is a quick explanation of the code:

$link = @mysql_pconnect("localhost","cat","dog") or exit();
mysql_select_db("myinfo") or exit();

These two lines tell PHP how to connect to the MySQL server.

$result = mysql_query("select name, salary from Employee");

This specifies up the query to be executed.

while ($row=mysql_fetch_row($result))
{
  print "<tr><td>" . $row[0] . "</td><td>" . $row[1] . "</td></tr>";
}

$row[0] denotes the first column of the query result, namely the "name" field, and $row[1] denotes the second column of the query result, namely the "salary" field. The . in the print statement is the concatenation operator, and acts to combine the string before and string after together. The print statement continuess until all 3 rows have been fetched.

Next: PHP Commands

Link to this page: If you find this page useful, we encourage you to link to this page. Simply copy and paste the code below to your website, blog, or profile.






Copyright 2007-2009  1keydata.com  All Rights Reserved.  Privacy Policy  



PHP Tutorial
PHP Variables
PHP Operators
PHP IF ELSE
PHP ELSEIF
PHP Switch
PHP While Loop
PHP FOR Loop
PHP DO WHILE Loop
PHP FOREACH Loop
PHP INCLUDE
PHP Functions
PHP ARRAY
PHP FORMS
PHP Cookies
PHP Redirect
PHP MySQL

PHP Commands

Resources