简体   繁体   中英

Proper way Javascript PHP MySQL

I have to insert in a MySQL database some data acquired from javascript. For send data to php script I use AJAX, $.POST of jQuery framework and mysqli function of PHP to insert data in the database.

javascript:

$.POST("insertData.php", {
  name1: val1,
  name2: val2,
  ...
}, function(data){
  console.log(data);
});

php script:

<?php
  $val1 = $_POST['name1'];
  $val2 = $_POST['name2'];
  ...

  $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

  $stmt = $mysqli->prepare('INSERT INTO tableName (name1, name2, ...) VALUES (?,?,...)');
  $stmt->bind_param('ss...', $val1 , $val2 , ...);

  $stmt->execute();

  $stmt->close();
  $mysqli->close();
?>

But with this method I must write the column name tree times, the first in javascript to send data with AJAX, the second in php to retrive data from $_POST and the last again in php to make the query.

There is any proper way to insert data in the MySQL database from Javascript where you should not write more times the columns names?

"Retrieving data from POST" is pointless. Just use $_POST['name1'] wherever you need it in the code, rather than assigning it to $val1 - you're actually wasting memory by needlessly duplicating your data that way ;)

For what it is worth, although I am not sure why would you want it, you could do something like this:

<?
  $columns = array_keys($_POST); //$columns is now array with column names
  foreach ($columns as $columns) echo $_POST[$column]; //get value for each column
  $columns = join(",",array_keys($_POST)); //$columns is now string name1,name2,...

  $values = array_values($_POST); //$values is now array with values
  $values = "'".join("','",array_values($_POST))."'"; //$values is now string 'value1','value2','value3',...

?> 

This is just basic array manipulation in PHP and I do not recommend using this for generating queries. since you can never be sure what will you get in $_POST and $_POST data in javascript in your example can be manipulated by end-user.

However, I am posting this just to show some basic techniques regarding your question.

Although it is a bad practice, you don't have to specify the column names in your query. If your POST is a 1-1 match with the columns, you can do:

  $input = rtrim(str_repeat('?,', count($_POST)), ',');
  $stmt = $mysqli->prepare("INSERT INTO tableName VALUES ($input)");
  array_shift($_POST, 'ss...');
  call_user_func_array(array($stmt, 'bind_param'), $_POST);

You can create an array of whitelisted column names that you will allow to be set on the PHP side prior to inserting. From this you explicitly state which columns are update-able/insert-able. Now you have a trusted list of keys.

Now you can either iterate the array of white list to dynamically build your SQL INSERT statement or iterate the POST array and for each key in your whitelist build a SQL statement from there. You can build different whitelist for different actions which map to different tables and with any luck you can use the same backend logic for multiple tables

Your can try somthing like this:

<?php
  $myvars = array ("name1"="","name2"="")
  foreach ($myvars as $key => &$vlaue)
  {
      if (isset $_POST[$key])
      {
          $value = $_POST['$key'];
      }
  }

  $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

  $stmt = $mysqli->prepare('INSERT INTO tableName ('.implode(", ",array_keys(myvars).')) VALUES '.trim(",",str_repeat("?, ", count($myvars)).')');
   $stmt->bind_param('ss...', $val1 , $val2 , ...);

  $stmt->execute();

  $stmt->close();
  $mysqli->close();
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM