Skip to content
Advertisement

How to INSERT simultaneously two different arrays in PDO MySQL?

I’m having trouble with a PDO insert. I’d like to insert a multidimensional array into a db, which i managed to. However, i also would like to insert a completely different array, disconnected from the first one into the same db line (which means same INSERT query). 1st multidimensional array = $_POST[‘training’] 2nd array = $training_diploma Kinda difficult to explain. Here is the code :

$id = "1";
$training_diploma = ("master", "bachelor");
$id_training_key = $id_training_key = $id.'_'.$training_diploma; (return: 1_master)

$sql = "INSERT INTO users_resumes (id,resume_category,id_training_key,training_diploma,training_school,training_level,training_start_date,training_end_date) VALUES ($id,'Training',$id_training_key,:training_diploma,:training_school,:training_level,:training_start_date,:training_end_date)";
$stmt= $pdo->prepare($sql);
foreach($_POST['training'] as $params){
   $stmt->execute($params);
}

Any help is very welcome !!! Thx a looot !

Advertisement

Answer

You need to iterate the $training_diploma array as well as the $_POST array. It would be better to also include the id and id_training_key as parameters in your query so you don’t have to prepare a new query for each set of values:

$id = "1";
$training_diploma = array("master", "bachelor");

$sql = "INSERT INTO users_resumes (id,resume_category,id_training_key,training_diploma,training_school,training_level,training_start_date,training_end_date) VALUES (:id,'Training',:id_training_key,:training_diploma,:training_school,:training_level,:training_start_date,:training_end_date)";
$stmt= $pdo->prepare($sql);
foreach($_POST['training'] as $params) {
    foreach ($training_diploma as $diploma) {
        $stmt->execute(array_merge($params, array('id' => $id, 'id_training_key' => $id . '_' . $diploma)));
    }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement