PHP Scripts – WordPress Tutorials

I have this example that can help you to create a PHP script to show a MySQL table as HTML. Its simple and easy to implement.

You might need this example when you are creating some application like Email Bot.. In that case you have to display your emails in one table in rows and data fields.

It can also be focused for displaying any kind of images Gallery that can display data on a single page. Note one thing that this example can only lead you to the idea and logic satisfaction. You have to improve this script in case of writing for some application that can be highly motivated as mentioned above.

In this example, we have to use following functions, So its necessary to know about these functions first.

  • mysql_connect - connects to MySQL server
  • mysql_select_db – select database
  • mysql_query - send query
  • mysql_num_fields - get number of fields
  • mysql_fetch_field - get field information
  • mysql_fetch_row - get current row from result table
  • mysql_free_result - free result table from memory

You can search more about these functions individually at PHP.net .

Now lets move to the PHP and script. You can write this Script using any of your editor.

You can change the variables values according to your server configuration(e.g $db_password, $db_user_name, $db_host_name, $database, $table)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<html><head><title>MySQL Table as HTML table Using PHP</title></head><body>
<?php
$db_host_name = 'localhost';
$db_user_name = 'root';
$db_password  = '123456789';
$database = 'dbcollege';
$table = 'tblstudents';
if (!mysql_connect($db_host_name$db_user_name$db_password))
die("Can not connect to the server");

if (!mysql_select_db($database))
die("Can not select database");

// Query Sending
$query = mysql_query("SELECT * FROM {$table}");
if (!$query) {
die("Query Failed");
}

$fields_num = mysql_num_fields($query);

echo "<h1>Table: {$table}</h1>";
echo "<table border='1'><tr>";
// Displaying table headers
for($i=0$i<$fields_num$i++)
{
$field = mysql_fetch_field($query);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// Displaying table rows
while($row = mysql_fetch_row($query))
{
echo "<tr>";

// $row is array

//  foreach( $ow as $cell) puts every element of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";

echo "</tr>\n";
}
mysql_free_result($query);
?>
</body></html>

This might not work and may have the possibilities of an error. So be care full about filling the server configuration variables as i have mentioned in the start of example.

Random Posts


Categories: PHP, Web Development
  • http://scienceinhand.com irfan korai

    oh really great , but i have a problem will you pleasemake a php table for my site?

    • http://www.computersneaker.com/ Mudasir Nazir

      Describe me your problem!
      I will do this for you!