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.

3 thoughts on “Making dynamic SQL queries from Javascript with PHP

  1. that a nice coding,,

    can you tell me how to get the result value of query into to a variable of the javascript itself ?

  2. Please tell me how would one call a query using mysql_fetch_assoc($result)

    SELECT COUNT(*) AS total FROM ow_base_user

    Your assistance in this would be much appreciated

Leave a Reply