Jquery ajax passing sql request

I am using an ajax call to query the database. I would like to pass a complex sql query as part of the ajax data. So am I supposed to do this?

var myQuery = 'select * from table....';        

$.ajax({
    type: "GET",
    url: 'jsonQuery.php',
    dataType: 'json',
    data: {keyvalue: 2416, q: myQuery},
    success: function(pieData) {
        //do something with the response        
    }

});

      

+3


source to share


3 answers


Yes, there is a better way. Save the request on the page .php

and submit a post type that tells you which one to use.

Example:



data: {keyvalue: 2416, q: 2},

      

Then you take your query matching number 2 and use that! No need to transfer SQL together!

+4


source


As others have argued, absolutely don't send direct SQL in the AJAX call. A hacker could easily write their own SQL query to execute whatever code they want on your database. Insead, you can POST several different field values ​​that you want to filter (for example, the value "name" or "key" or "age_range"). Then configure PHP on the receiving end to be smart when to use these values; if a key is present, use that as an identifier and use the X query. If the key is not present, check that the name or other values ​​look up the right row and insert them into the Y query.

As IngodItrust reports, you can also send a POST value that indicates which request to use, i.e.

q: 'LongerQuery'

      



then there are several IF or CASE statements in the receiving PHP that prepare another query depending on which Q value is present.

I have a chart generator on my site where the user can change the settings for the data that is passed along the X and Y axes, regardless of whether the data is split into different series and how the data pool should be filtered if the user only wants to look at a specific demographic ... These settings are sent via AJAX / POST when the user clicks the "Create" button. The PHP receiving page builds a request for chart data based on these 20 inputs; the resulting queries may look very different depending on the settings the user chooses. I'm describing this to illustrate that AJAX can be used to create extremely flexible and responsive requests without compromising security.

+1


source


You shouldn't actually be passing any SQL to jsonQuery.php if that's what I understand. This will open a SQL injection attack. See http://bobby-tables.com/ for Google only.

Rather pass parameters to your script like jsonQuery.php? do = SEARCH & itemID = 12 & type = RED_ONES and create your query in jsonQuery.php using these parameters. Eat each of the expected values ​​earlier than ..

0


source







All Articles