Example to process a MySQL table in PHP

MySQL Select: Example

This source code creates a webform. The user is allowed to enter the name of a database, a table, the fields' names, the field count and optional where clause. It displays all the records from the specified table in tabular format. Try it yourself by saving the source at your local machine as "select_records.php" ! Do not forget to specify proper hostname, user id and password. With this we come to the end of the mysql tutorial also. Do visit this section for more updates.


<html>
<head>
<title>Example to retrieve data from a MySQL table</title>
</head>
<body>

<?php
//Retrieve the database and table name
$fldcount = 0;
$database = $_GET["db"];
$table = $_GET["table"];
$flds = $_GET["flds_names"];
$fldcount = $_GET["fld_count"];
$where = $_GET["where"];

//Continue if database name is non blank
if($database!="" && $table!="" && $flds != "")
{
$sql_statement = "Select ".$flds." from ".$table." ".$where;

//Connect to the MySQL Database
$conn = mysql_connect ("host","userid", "password");;

//Select the database
mysql_select_db($database,$conn);

//Execute query to retrieve the resultset
$resultset = mysql_query($sql_statement,$conn) or
die("Could not update table");

if($resultset!=null){
//Throw success message;
echo "Displaying all the records (".$where.") from ".
$table. " in database ". $database;
//Begin the table
echo "<table>";

//Iterate over all the rows of the resultset
while($row = mysql_fetch_rows($resultset,$conn))
{
//Initialize the counter. This is the no. of columns processed
$count = 0;
echo "<tr>";

//Loop thorugh all the columns
while($count < $fldcount){

//Print one column value in a table cell.
echo "<td>".$row[$count]."</td>";

//Increment the counter to print the next column value.
$count++;
}

//Close the row. New row will be started if
there are more rows in the resultset.
echo "</tr>";
}

//Close the table
echo "</table>";
}
}
?>

<form action="select_records.php">
<table align=center>
<tr><td>Database Name:</td><td><input type=text name=db></td></tr>
<tr><td>Table Name:</td><td><input type=text name=table></td></tr>
<tr><td>Fields Name (*) for all:</td><td><input type=text name=flds_names></td></tr>

<tr><td>Field Count:</td><td><input type=text name=fld_count></td></tr>

<tr><td>Where Clause:</td><td><input type=text name=where></td></tr>
</form>
</body>
</html>