Jump to content

Fetch data from database with PHP and AJAX

Recommended Posts

First off, thanks for letting me into the forums.

Excuse a newbie but I have a question about fetching data from a database with PHP and AJAX.

Let's say I wanted to fetch data from the database like in this example from W3Schools, but I had modified the dropdown to for example fetch all entries with last name Griffin, Swanson or Quagmire. I made the q variable take a string instead of an integer.

$q = strval($_GET['q']);

Now I want to expand the SQL query to also take another condition.

"SELECT * FROM user WHERE LastName = '".$q."' AND Hometown = '".$q2."'";

I understand how to build the query and that I need to declare another variable (q2), but how do I modify the AJAX request?


 Also, would I need to have a submit button now that there are two conditions?


Share this post

Link to post
Share on other sites

IF you are talking about multiple selection dropdown the value would contain 'Griffin,Swanson,Quagmire', so you would not need to change JavaScript, only the php side to split those names from $_GET['q']

For passing second variable, you have to run a function to retrieve the two values and apply to variables 'str' sames as before, and lets say 'home', then in ajax querystring


Then in php

$homeTown = strval($_GET['hometown']);


  • Like 1

Share this post

Link to post
Share on other sites

If you're sending string values in the URL then you'll also want to use the encodeURIComponent function to make sure the values don't break the URL.  Otherwise, if you're sending a lot of data you'll probably want to just switch to a post request instead of a get request.

  • Like 1

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...