我正在处理包含复选框和MySQL数据库的PHP表单。我终于实现了通过在数组上循环来插入多行,每个行对应一个选定的项。
但是现在,我不得不面对另一个问题:在我的数据库中,我有一个主体表来存储单选问题,并有另一个表来存储复选框的答案。
我想首先执行将单选答案插入主体表(每种形式一行)的查询,以便生成序列ID。
其次,要获取此ID并将其与插入到复选框表中的每一行相关联,以便通过此ID链接两个表。
请问那可能吗,我该怎么办?


这里的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:

$lastInsertedID = $db->lastInsertId();


1.)将问题插入数据库表(主要)

2.)获取最后插入的ID($ lastInsertedID)

3.)在答案表中插入与问题相关的答案,并提供最后插入的ID。

$query = "INSERT INTO nmp_mfs.t_temporaire (questionID, nature_contact)
VALUES ($lastInsertedID, $nature_contact)"; // Example


4.)选择您的问题的ID。

5)得到相应的答案:

$query = "SELECT awnsers WHERE question_id = questionID"; // Simple example

关于php - 如何使用外键将数据从PHP表单插入MySQL数据库?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38243647/

10-14 16:02
查看更多