Tag Archives: AJAX

Making dynamic SQL queries from Javascript with PHP

Impossible? No!

Just add some AJAX to your <head> section:
<script type="text/javascript">
function request(query){
if (window.XMLHttpRequest){xmlhttp=new XMLHttpRequest();}
else{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
if (xmlhttp.readyState==4 && xmlhttp.status==200){
//it worked.
alert(xmlhttp.responseText); //this is the output of your query.php file
}else{
//whatever happens when it doesn't work
alert('Query did not work');
}
xmlhttp.open("GET","query.php?q="+query,true);
xmlhttp.send();
}
</script>

and create the new page query.php with the following content, replacing the default values where necessary:

<?php
$dbhost = '#REPLACE THIS#';
$dbuser = '#REPLACE THIS#';
$dbpass = '#REPLACE THIS#';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$dbname = '#REPLACE THIS#';
mysql_select_db($dbname);
$query=$_GET["query"];
$result = mysql_query($query);
//now use mysql_fetch_assoc($result) or something similar to get the returned result if applicable.
//if you echo a value, the javascript ajax will receive it
?>

Using this code, you can make whatever kind of SQL queries you want from other sections of your site.

Warning: Unless you sanitize your database inputs you leave yourself open to some huge vulnerabilities.