Skip to content

Instantly share code, notes, and snippets.

@theoperatore
Created June 5, 2013 21:08
Show Gist options
  • Save theoperatore/5717333 to your computer and use it in GitHub Desktop.
Save theoperatore/5717333 to your computer and use it in GitHub Desktop.
simple php to query a connected database using AJAX. Important: USE OF DO WHILE LOOP!
<?php
require_once('db_connect.php');
if ($con) {
$select = $_POST['select'];
$from = $_POST['from'];
$where = $_POST['where'];
$where_param = $_POST['where_param'];
//strip of trailing or leading whitespace
$where_param = trim($where_param);
//only match letters in the given paramter one or more times
preg_match("([a-zA-Z]+)", $where_param, $matches);
//if $where_param isn't empty...
if (strlen($where_param) != 0) {
//use it in the query
$query = "SELECT $select FROM $from WHERE $where='" . $matches[0] . "'";
}
//otherwise omit
else {
$query = "SELECT $select FROM $from";
}
//DEBUGGING ONLY
echo $query;
//query the database
$result = mysql_query($query);
}
else {
die("Connection is False");
}
echo "<div class='columns'><ul>";
//if the syntax was correct for the query...
if ($result) {
//first check to see if anything was returned from the database
if ($arr = mysql_fetch_array($result)) {
//if it was, then return the first element of the query resource...
do {
//DEBUG; dump the var for now
echo var_dump($arr);
//as long as there are more elements in the resource...
} while ($arr = mysql_fetch_array($result));
}
//nothing matched the query
else {
echo 'No matches to your query...';
}
}
else {
echo 'Unkown Query Syntax...';
}
//close the html returned
echo "</ul></div>";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment