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
//whatever happens when it doesn't work
alert('Query did not work');

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

$dbhost = '#REPLACE THIS#';
$dbuser = '#REPLACE THIS#';
$dbpass = '#REPLACE THIS#';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$dbname = '#REPLACE THIS#';
$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.