简体   繁体   中英

PHP: insert array with seperate lines into database as values

I am passing an array through ajax to PHP where I want to insert them as a row in mysql. Is there a way i can do that?

Javascript:

var textarray = [];
for(var i = 0; i<data.length; i++){
  var sms = $('#TxtMessage').val();
  var brand = data[i].brand;
  var type = data[i].type;
  var csvLine = `${sms}, ${brand}, ${type} `;
  textarray.push(csvLine)
}

var resultCSV = textarray.join('\n');

//Pass the array to PHP
$.ajax({
  type: "POST",
  url: "../php/functions.php",
  data: { results: resultCSV },
  success: function(data) {
       console.log(data);
  }
});

In PHP i would like to insert each row into mysql database. The values I pass to PHP look like this

sample text, Toyota, 30/10/2008 10:00:00 
sample text, Nissan, 17/02/2021 14:00:00 

so each row of the text should go in as a row into the database.

PHP:

$myArray = $_POST['results'];
$columns = implode(" ",array_keys($myArray));
$escaped_values = array_map('mysql_real_escape_string', array_values($myArray));
$values  = implode(", ", $escaped_values);
$sql = "INSERT INTO `databasetable`($columns) VALUES ($values)";

What people usually do is use something like json to encode and decode their data they pass. It is much easier than what you are doing.

You encode like

$myVar = json_encode($dataArray);

You decode like

$myReturn = json_decode($_POST['csvDataArray']);

If you want to convert csv to array you can use

$mycsvArray = array_map("str_getcsv", explode("\n", $csv));

You may have to stripslashes.

Then it is as simple as looping to build your query. Something like this.

$myQuery = array();
foreach($myCSVArray as $rowArray) {
  $myQuery[] = INSERT INTO `databasetable`($columns) VALUES ($escaped_values);
}

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