How to secure SQL queries send from the client?
16:15 08 May 2013

For prototyping, I often use a self-built plugin where i an do something like this

$.databaseContents({
   url: '/sqliquery.php',
   data : {query : 'SELECT * FROM members WHERE id = 45'}
});

The php script will execute the query and return a JSON-encoded result.

In a localhost environment I obviously don't worry about securing my server from malicious intent.

So I wonder, what would I best do if I actually wanted to deploy this on a live website? I'm not keen on doing a lot of unnecessary security engineering - it's not like I'm going to be getting 12,000 hits a day. But I'd like to be sure that I don't end up having my database injected with nasty queries.

After some reading, my impression is that I can simply secure the php query variable by doing mysql_real_escape_string($_POST["query"]); but that seems not really safe - Can't someone just directly interact with a php script and submit data by spoofing the host or something? I'm not very familiar with this stuff.

I thought maybe allowing only a specific URL to access it would be good. Or is can that be circumvented easily?

php sql security cross-domain