J'ai un script qui insère dans deux tables de base de données séparées: les ingrédients et les directions. Pour la première fois, j'utilise $this->db->query($sql)
, et pour la seconde: $this->db->query($sql2)
(j'utilise CodeIgniter). Voici mon code:Les inserts de base de données sont combinés?
foreach($_POST as $key => $value) {
$value = $this->input->post($key);
$directions = $this->input->post('directions');
$ingredientQTY = $this->input->post('ingredientQTY');
$measurements = $this->input->post('measurements');
$ingredientNAME = $this->input->post('ingredientNAME');
$ingredientsROW[] = array($ingredientQTY, $measurements, $ingredientNAME);
//For inserting ingredients
for ($i = 0, $count = count($ingredientQTY); $i < $count; $i++) {
$rows[] = array(
'ingredientamount' => $ingredientQTY[$i],
'ingredientType' => $measurements[$i],
'ingredientname' => $ingredientNAME[$i],
'recipe_id' => $recipe_id,
'order' => $i + 1,
'user_id' => $user_id
);
$sql = "INSERT `ingredients` (`ingredientamount`,`ingredientType`,`ingredientname`,`recipe_id`, `listOrder`, `user_id`) VALUES ";
$coma = '';
foreach ($rows as $oneRow) {
$sql .= $coma."('".implode("','",$oneRow)."')";
$coma = ', ';
}
}
$this->db->query($sql);//Insert Query for ingredients
//For inserting directions
for ($i = 0, $count = count($directions); $i < $count; $i++) {
$rows[] = array(
'direction' => $directions[$i],
'recipe_id' => $recipe_id,
'order' => $i + 1,
'user_id' => $user_id
);
$sql2 = "INSERT `directions` (`direction`,`recipe_id`,`listOrder`,`user_id`) VALUES ";
$coma = '';
foreach ($rows as $oneRow) {
$sql2 .= $coma."('".implode("','",$oneRow)."')";
$coma = ', ';
}
}
$this->db->query($sql2); //Insert Query for directions
break;
}
Je devrais avoir deux instructions SQL séparées, mais pour une raison quelconque, ils sont combinés en et générer l'erreur suivante:
Column count doesn't match value count at row 1
INSERT `directions` (`direction`,`recipe_id`,`listOrder`,`user_id`) VALUES ('1','Bunch','Cilantro','1','1','1'), ('3','Cup','Sugar','1','2','1'), ('First, combine the cilantro and sugar','1','1','1'), ('then eat. ','1','2','1')
Il devrait y avoir un INSERT ingredients
ainsi , mais ses valeurs sont combinées dans l'instruction INSERT directions
.
Pourquoi les deux instructions SQL seraient-elles combinées?
@PreetSangha, Il y a 2 en compte ($ directions) – Muhambi