Home > Software design >  AJAX JQuery PHP Convert name to match query columns with the data sent with POST variable
AJAX JQuery PHP Convert name to match query columns with the data sent with POST variable

Time:10-20

My question really is with PHP accepting with my ajax request

  $("#addUser").on('click', '.btnAddSubmitFormModal', function() {

  $.post("add.php",
  {
      firstName: $("#modalFormAddFirstName").val(),
      lastName: $("#modalFormAddLastName").val(),
      middleName: $("#modalFormAddMiddleName").val(),
  })
  .done(function (result, status, xhr) {
  //Some codes here
  });

and my insert query is like this

    $keys = array();
    $values = array();
    foreach ($_POST as $column) {
    $value = trim($_POST[$column]);
    $value = mysql_real_escape_string($value);
    $keys[] = "`{$column}`";
    $values[] = "'{$value}'";
}

$query = "INSERT INTO 'table' (" . implode(",", $keys) . ") 
          VALUES (" . implode(",", $values) . ");";

The question I have is with data name being sent to match and work with columns in table, any efficient way to convert my columns sent by ajax like a translator something?

firstName(Javascript) to first_name(Mysql column) to match and work with insert?

$_POST['firstName'] to $_POST['first_name']?

My question is actually asking for suggestions on how would you do it? instead of just transferring to other name buy unseting it. I was thinking about it. Like:

$_POST['first_name'] = $_POST['firstName'];
unset($_POST['firstName']);

Is there other way to do what I am doing right now?

CodePudding user response:

You should use a prepared statement. It will solve this problem for you as you can code the column names directly into the INSERT, as well as protecting you from SQL injection. It also removes the need to escape strings. For mysqli:

$stmt = mysqli_prepare(INSERT INTO `table` (first_name, last_name, middle_name) VALUES (?, ?, ?)");
$stmt->bind_param('sss', $_POST['firstName'], $_POST['lastName'], $_POST['middleName']);
$stmt->execute();

Note I see you are using mysql_real_escape_string in your code. If you are still using mysql_* functions, you need to upgrade, at least to MySQLi, but preferably to PDO.

  • Related