Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to encode/decode query parameters between an ajax request and the php receiving that request?

Tags:

jquery

ajax

sql

php

I want to send whole sql command through ajax call as a argument. Do I have to do escape it or to do something special about that?

Something like tools.php?database=db2&sql=select * from table

If escaping is necessary

  • how do I do it in javascript/jquery
  • what do I do then in php to read it

NOTE - very specific use-case & system settings

The web server is accessible only from inside our internal network. If anybody breaks in they can get all the databases so my 'little application' with I am improving via this question is not important at all. I have already implemented DROPping of whole database, updating whole columns, updating db's settings etc via my web application. I just want to add this new feature. I might even happen that I am going to be the only use of this web application.

like image 947
Radek Avatar asked Nov 27 '22 18:11

Radek


2 Answers

There is no reason you should be building an SQL query client-side. If you're building a system that might be an exception to this rule, you wouldn't be asking this question here.

Send basic information in the AJAX request, and use that info to build a query.

Use PDO and parameterised queries to protect yourself from SQL Injection attacks.

like image 113
Stephen Avatar answered Nov 30 '22 08:11

Stephen


PEOPLE, DON'T USE THIS CODE IF YOU ARE NOT ABSOLUTELY SURE WHAT YOU ARE DOING

This code is subject to catastrophical security breaches, so don't use it unless you absolutely sure that no evil people will access it.

Sending:

jQuery.ajax({
    type: 'post',
    dataType: 'json',
    url: *your backend url here*,
    data: {database: 'db', sql: "select * from table"},
    success: function(data, textStatus){
        //perform any processing with data returned from backend here
    }
});

Receiving:

<?php
    $sql = $_POST['sql'];
    $db = $_POST['db'];
    //db connection
    $result = mysql_query($sql);
    //processing query result, $rslt is processing result
    echo json_encode($rslt);
?>

Hovewer, it's not a good idea to send SQL from client, such an approach is extremely vulnerable to SQL-injections. But, if you are sure you want to shoot yourself in a leg...

like image 45
J0HN Avatar answered Nov 30 '22 06:11

J0HN