JavaScript: How to Get a MySQL Query Via PHP

Written by steve mcdonnell Google
  • Share
  • Tweet
  • Share
  • Email

The PHP scripting language is best suited to run MySQL queries because it is a server-side scripting language. However, it is possible to use JavaScript, a client-side scripting language, to get MySQL query results from a PHP program. To do this, you first need to declare a JavaScript function to receive the query results in JavaScript Standard Object Notation (JSON). You then need to create a PHP/MySQL program in an external file and have the PHP script run the query, convert the results to JSON and echo the JavaScript function with the results as a parameter to the JavaScript function.

Skill level:


  1. 1

    Create a new PHP file using Notepad or an editor of your choice. Accept a URL parameter called "query" that will serve as the query filter:


    $selection = $_GET["query"] or die("No query parameter passed!");

  2. 2

    Connect to the MySQL database server and select the MySQL database that has the table you want to query:

    $dbc = mysql_connect("localhost", "username", "password") or die(mysql_error());

    $dB = mysql_select_db("database") or die(mysql_error());

  3. 3

    Create the query string to select a record from the database based on the query parameter passed in the URL. Run the query:

    $query = sprintf('SELECT * FROM users WHERE name="%s" LIMIT 1', $selection);

    $result = mysql_query($query) or die(mysql_error());

  4. 4

    Encode the results in JSON. Echo the name of the JavaScript function you will create with the JSON-encoded results as the parameter to that function:

    $row = json_encode(mysql_fetch_assoc($result));

    echo "query Results('" . $result . "');";


  1. 1

    Create a new HTML document with Notepad or an HTML editor. Insert the HTML headers into the page:




    <meta charset="utf-8">

    <title>JavaScript Get MySQL Query from PHP</title>

  2. 2

    Create a JavaScript function that will receive JSON-encoded data and display the results. Assign the same name to the JavaScript function as you used with the PHP script.


    function query Results(data) {

    var results = JSON.parse(data);

    document.write("<p>Name = " + + "</p>");

    document.write("<p>e-mail = " + + "</p>");


  3. 3

    Add another script and assign the source to be the URL of the PHP script, including the query string:

    <script src=""></script>


  4. 4

    Add a blank "body" to the Web page and close the HTML tag:




  5. 5

    Open the HTML document in a browser and check to make sure it correctly displays a user's name and e-mail address.

Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.