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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now