我正在处理一个包含复选框和MySQL数据库的PHP表单。我终于实现了通过遍历数组插入多行,每个行选择一个项目。
但现在,我不得不面对另一个问题:在我的数据库中,我有一个主表来存储单选题和另一个表来存储复选框的答案。
我想先执行查询插入主表(单表格每行一个选择答案),以便它生成一个序列号。
其次,要取回此ID并将其与每个插入到复选框表中的行相关联,以便通过此ID链接这两个表。
请问我该怎么办?
如何将数据从PHP表单插入到具有外键的MySQL数据库中?
这里的HTML代码:
<input type="checkbox" name="nature_contact[]" value="1"><label >Phone</label><br/>
<input type="checkbox" name="nature_contact[]" value="2"><label >Mail</label><br/>
<input type="checkbox" name="nature_contact[]" value="3"><label >Visit</label><br/>
<input type="checkbox" name="nature_contact[]" value="4"><label >Unk</label> <br/><br/>
<input type="text" name="coord"/>
<br/>
<input type="text" name="tel"/>
<br/><br/>
<input type="submit" name="add" value="SEND"/>
这里PHP的一部分:
try {
if(isset($_POST['add'])){
if(isset($_POST['coord'])) {
$coord=$_POST['coord'];
}
else { $coord = '';
}
if(isset($_POST['tel'])) {
$tel=$_POST['tel'];
}
else { $tel = '';
}
$query="INSERT INTO nmp_mfs.general (coord, tel) VALUES ('".$coord."', '".$tel."')";
$statement_gnl = $pdo->prepare($query);
$statement_gnl->execute();
}
}
catch(PDOException $e) {
$msg = 'ERREUR PDO dans ' . $e->getFile() . ' L.' . $e->getLine() . ' : ' . $e->getMessage();
die($msg);
}
try {
if(isset($_POST['add'])){
if(isset($_POST['nature_contact'])) {
$sql = "INSERT INTO nmp_mfs.t_temporaire (nature_contact) VALUES ".rtrim(str_repeat('(?),', count($_POST["nature_contact"])), ',');
$statement = $pdo->prepare($sql);
$count = 1;
foreach($_POST["nature_contact"] as $nature_contact) {
$statement->bindValue($count++, $nature_contact);
}
$statement->execute();
}
}
}
catch(PDOException $e) {
$msg = 'ERREUR PDO dans ' . $e->getFile() . ' L.' . $e->getLine() . ' : ' . $e->getMessage();
die($msg);
}
谢谢!我试着用(最大id),但lastInsertId()更可靠。但是,我需要将此值添加到函数中:.rtrim(str_repeat('(?),',count($ _ POST [“nature_contact”])),','),这对我来说很棘手。我尝试了str_repeat('($ lastID,?)'),但是它重新调用了一个字符串,而不是$ lastID中的值。是否可以解决? – RemiC
它工作!我忘了引号:str_repeat('('。$ lastID ',?),' – RemiC