Friday, October 18, 2013

SQL Query Form Design Pattern Using mysqli

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


<html>
<head>
<title>MySQL mysqli 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 mysqli Query Interface</h1>";
echo "<form action='mysql_mysqli_query.php' method='post'><textarea cols='80' rows='5' name='sql'>";
echo "$sql";
echo "</textarea><br /><input type='submit'></form>";

# Connection Check
$testcon = mysqli_connect("$host", "$user", "$pw", "$db") 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 $con = new mysqli("$host", "$user", "$pw", "$db"); $result = $con->query("$sql"); $num_rows = $result->num_rows; $num_cols = $result->field_count; echo "Rows: ".$num_rows."<br />"; echo "Columns: ".$num_cols."<hr />"; # Table Heading echo "<table border='1'>"; while ( $col = $result->fetch_field() ) { $fn = $col->name; echo "<th>".$fn."</th>"; } # Table Content while ( $row = $result->fetch_array() ) { echo "<tr>"; $c = 0; while ( $c < $num_cols ) { echo "<td>".$row[$c]."   </td.>"; $c = $c+1; } echo "</tr>"; } echo "</table>"; ?> </body> </html>

No comments: