У меня есть одна форма, при отправке которой я хочу вставить одну запись, затем получить последний вставленный идентификатор и затем вставить несколько строк в другую таблицу.
Я могу правильно понять первую часть, но не вторую.
public function save($data)
{
$this->customer_id = $data['customer_id'];
$this->description = $data['description'];
$this->line_description = $data['line_description'];
$this->line_amount = $data['line_amount'];
$this->validate();
if (empty($this->errors)) {
$db = static::getDB();
$stmt = $db->prepare("INSERT INTO `invoices` (`customer_id`) VALUES (:customer_id)");
$stmt->bindValue(":customer_id", $this->customer_id, PDO::PARAM_INT);
$stmt->execute();
$last_id = $db->lastInsertId();
$db = static::getDB();
$stmt = $db->prepare("INSERT INTO `lines` (`description`, `amount`, `invoice_id`) VALUES (:description, :amount, :invoice_id)");
$stmt->bindValue(":description", $this->line_description, PDO::PARAM_STR);
$stmt->bindValue(":amount", $this->line_amount, PDO::PARAM_STR);
$stmt->bindValue(":invoice_id", $last_id, PDO::PARAM_INT);
// foreach loop here ?
$stmt->execute();
// end foreach
}
}
$ data в публичной функции save ($ data) выглядело бы так, если бы var_dumped
array(5) {
["customer_id"]=> string(2) "16"
["description"]=> string(4) "test"
["amount"]=> string(0) ""
["line_description"]=> array(2) {
[0]=> string(5) "desc1"
[1]=> string(4) "desc"
}
["line_amount"]=> array(2) {
[0]=> string(3) "123"
[1]=> string(3) "456"
}
}
Входные данные HTML:
<input type="text" class="form-control" placeholder="Line Description" name="line_description[]">
<input type="text" class="form-control" placeholder="Description" name="description">