0

Is it OK to use table column names as keys in a key/val pair on the JS side when making XHR/AJAX requests?

In JS, I'll do something like this, where I specify the data to insert into the table, using actual table column names as keys in the key/val pair:

function createAccount() {

  var params = {
    name : 'John Smith',
    city : 'New Orleans',
    phone : '000-111-2222'
  };

  makeApiCall('/account', params, 'POST');

}

Then in the middle tier, I'll do something like this, where I simply pass the data right into the code that inserts into the DB ($args):

  public function createAccount($response, $args) {

    $trans = $this->db->insert('accounts', $args);

  }

This certainly is much easier for me. Less code to write, but am wondering what the cons are to doing this?

1

There is a downside to using the same keys in JavaScript as column names in the database. A strong coupling like you're suggesting will probably break your frontend if you attempt to rename a database column. It's better to introduce some kind of mapping from frontend keys to database columns to protect you from changes like that.

The other thing to be careful of is the possibility of SQL injection when using user input to query the database. You should use best practices when querying your database including using prepared statements and sanitising user input.

  • The likelihood of breaking frontend upon renaming a database column if a mapper is used is the same. If anything, the solution would decouple the "DAO" aspect of the program from the rest of the backend creating a slightly more robust program, but I suppose that could be done at any point, not necessarily when all columns match. – Neil Jun 13 '17 at 7:30
  • So if I were to protect against sql injection using parameterized queries, would this be acceptable? – Freddie Jun 14 '17 at 3:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.