Friday, October 18, 2013

SQL Query Form Design Pattern Using mysql

The following is a PHP Script that can serve as a design pattern for HTML form handling with "mysql" connection driver for the MySQL database.



<html>
<head>
<title>MySQL mysql Query Interface</title>
<!--
Clement L. Rasul
copyright (c) 2013
-->
</head>
<body>

<?php
$sql = trim($_POST['sql']);
$host = "localhost";
$user = "root";
$pw = "wordpass123";
$db = "testdb";

# Query Form
echo "<h1>MySQL mysql Query Interface</h1>";
echo "<form action='mysql_mysql_query.php' method='post'><textarea cols='80' rows='5' name='sql'>";
echo "$sql";
echo "</textarea><br /><input type='submit'></form>";

# Connection Check
$con = mysql_connect( $host, $user, $pw );
mysql_select_db( $db , $con) or 
  die ("Database Status: <font color='red'><blink><b>Connection Error!</b></blink></font>");
echo "Database Status:  <font color='green'><blink><b>Connected...</b></blink></font><hr />";

# SQL Query Script
$result = mysql_query( $sql , $con) or die(mysql_error());
$num_rows = mysql_num_rows($result);
$num_cols = mysql_num_fields($result);
echo "Rows: ".$num_rows."<br />";
echo "Columns: ".$num_cols."<hr />";
echo "<table border='1'>";

# Table Heading
$f=0;
while ( $col = mysql_field_name($result, $f) ) {
	$fn = $col;
	echo "<th>".$fn."</th>";
	$f=$f+1;
    	}

# Table Content
while ( $row = mysql_fetch_array($result) ) {
	echo "<tr>";
	$c = 0;
	while ( $c < $num_cols ) {
		echo "<td>".$row[$c]."   </td.>";
		$c = $c+1;
		}
	echo "</tr>";
    	}
echo "</table>";

?>
</body>
</html>


No comments: