Friday, October 18, 2013

SQL Query Form Design Pattern Using "MySQL PDO" driver

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


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

# Connection Check
try {
    $con = new PDO('mysql:host='.$host.';dbname='.$db.'', $user, $pw );
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	echo "Database Status:  <font color='green'><blink><b>Connected...</b></blink></font><hr />";
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

# SQL Query Script
$result = $con->query(''.$sql.'');
$num_rows = $result->rowCount();
$num_cols = $result->columnCount();
echo "Rows: ".$num_rows."<br />";
echo "Columns: ".$num_cols."<hr />";
echo "<table border='1'>";

# Table Heading
for ($i = 0; $i < $result->columnCount(); $i++) {
    $col = $result->getColumnMeta($i);
    $columns[] = $col['name'];
}

$f=0;
while ( $f < $num_cols ) {
	$fn = $columns[$f];
	echo "<th>".$fn."</th>";
	$f=$f+1;
    	}

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

?>

</body>
</html>


No comments: