R
R
Rinat2015-09-22 07:44:50
PHP
Rinat, 2015-09-22 07:44:50

How to organize a multiquery of an array of data?

Good afternoon ! Faced with a problem: How to organize a multi-request for adding rows to a table, depending on the number of data received (on the machine). there is a code

if (isset($_POST['data_oper_tas'])) { $data_oper_tas = $_POST['data_oper_tas']; if ($data_oper_tas == '') { unset($data_oper_tas);}}
  if (isset($_POST['check_func'])){
    $formatos_check=implode(',',$_POST['check_func']);
  }
array (size=2)
  'data_oper_tas' => string '2015-09-14' (length=10)
  'check_func' => 
    array (size=5)
      0 => string '16' (length=2)
      1 => string '7' (length=1)
      2 => string '8' (length=1)
      3 => string '10' (length=2)
      4 => string '11' (length=2)
$sql="INSERT INTO dateplan VALUES ('$formatos_check','$data_oper_tas') ";

you need something like this
$sql="INSERT INTO dateplan 
VALUES ('16','2015-09-14'), ('16','2015-09-14'),
('7','2015-09-14'), ('8','2015-09-14') ,
('10','2015-09-14'),('11','2015-09-14')  ";

Thanks a lot, everyone !

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
heartdevil, 2015-09-22
@WaRstim

Hello.
The request should be of the form

INSERT INTO dateplan
  (id_tas_dat, date_dat)
VALUES
(16, '2015-09-14'),
(7, '2015-09-14'),
(8, '2015-09-14'),
(10, '2015-09-14'),
(11, '2015-09-14')

To form it:
Read the date from the array['data_oper_tas'] array, then read the IDs in the array['check_func'][0], array['check_func'][1] and so on and form a multiinsert request.
UPD:
Here is an example algorithm (this is not a working code). You will need to correct it and make checks in the input parameters.
$inserts = '';
$date = $_POST['data_oper_tas'];

for ($i = 0, $i < count($_POST['check_func']); $i++)
{
  $inserts .= '('. $_POST['check_func'][$i] .','. $date .'),';
}

$insertQuery = 'INSERT INTO dateplan (id_tas_dat, date_dat) VALUES ';

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

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
$stmt = $mysqli->prepare($insertQuery . rtrim($inserts, ','));
$stmt->execute();
$stmt->close();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question