Pages

PHP 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.

If you like this please Link Back to this article...



0 comments:

Post a Comment