You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中使用inner join将下拉菜单值插入数据库两张关联表

实现方案

现有代码核心问题

  • INSERT语法错误:INSERT语句不支持后跟FROM、JOIN子句,你编写的SQL结构不符合MySQL语法规范
  • 字段不匹配:posts表不存在auteur字段,仅存储关联的auteur_id外键,无法直接插入作者名称
  • 严重SQL注入风险:直接拼接用户提交的参数到SQL语句,易被注入攻击
  • 错误处理逻辑错误:console.error是JavaScript API,PHP无法调用,且catch语句未声明捕获的异常类型
  • 下拉选项写死:后续新增作者需要手动修改前端代码,扩展性差

优化实现步骤

步骤1:修改下拉选择框,动态加载作者数据

直接将作者ID作为下拉选项的value提交,无需后续额外关联查询,同时动态读取auteurs表数据,后续新增作者无需修改前端代码:

<select name='auteur_id'>
<?php
// 从auteurs表读取所有作者
$auteurs = $conn->query("SELECT id, auteur FROM auteurs")->fetchAll(PDO::FETCH_ASSOC);
foreach($auteurs as $item) {
    echo "<option value='{$item['id']}'>{$item['auteur']}</option>";
}
?>
</select>

步骤2:修改提交逻辑,使用预处理语句插入数据

修正SQL写法,用参数绑定避免SQL注入:

if (isset($_POST["submit"])) {
    $titel = $_POST['titel'];
    $img = $_POST['img_url'];
    $inhoud = $_POST['inhoud'];
    $auteur_id = $_POST['auteur_id'];
    // 预处理SQL,参数绑定
    $stmt = $conn->prepare("INSERT INTO posts (titel, img_url, inhoud, auteur_id) VALUES (?,?,?,?)");
    $stmt->execute([$titel, $img, $inhoud, $auteur_id]);
    // 插入成功后跳转,避免重复提交
    header('Location: index.php');
    exit;
}

如果你确实需要通过作者名匹配ID插入(不推荐,效率更低)

可以使用INSERT ... SELECT语法,不需要单独执行查询语句:

$stmt = $conn->prepare("INSERT INTO posts (titel, img_url, inhoud, auteur_id) SELECT ?,?,?,id FROM auteurs WHERE auteur = ?");
$stmt->execute([$titel, $img, $inhoud, $auteur]);

完整修正后代码

<html>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div class="container">
        <div id="header">
            <h1>新帖子</h1>
            <a href="index.php"><button>所有帖子</button></a>
        </div>
        <?php
            $host = 'localhost';
            $username = 'root';
            $password = '';
            $dbname = 'foodblog';
            
            try {
                $conn = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch (PDOException $e) {
                echo "连接失败: " . $e->getMessage();
                exit;
            }
            
            try {
                if (isset($_POST["submit"])) {
                    $titel = $_POST['titel'];
                    $img = $_POST['img_url'];
                    $inhoud = $_POST['inhoud'];
                    $auteur_id = $_POST['auteur_id'];
                    
                    $stmt = $conn->prepare("INSERT INTO posts (titel, img_url, inhoud, auteur_id) VALUES (?,?,?,?)");
                    $stmt->execute([$titel, $img, $inhoud, $auteur_id]);
                    
                    header('Location: index.php');
                    exit;
                } else {
            ?>
            <form action="new_post.php" method="post">
                标题:<br/> <input type="text" name="titel"><br/><br/>
                作者:<br>
                <select name='auteur_id'>
                <?php
                $auteurs = $conn->query("SELECT id, auteur FROM auteurs")->fetchAll(PDO::FETCH_ASSOC);
                foreach($auteurs as $item) {
                    echo "<option value='{$item['id']}'>{$item['auteur']}</option>";
                }
                ?>
                </select>
                <br><br>
                图片URL:<br/> <input type="text" name="img_url"><br/><br/>
                内容:<br/> <textarea name="inhoud" rows="10" cols="100"></textarea>
                <br/><br/>
                <input type="submit" name="submit" value="发布">
            </form>
            <?php
                }
            } catch(PDOException $e) {
                echo "操作失败: " . $e->getMessage();
            }
        ?>
    </div>
</body>
</html>

内容的提问来源于stack exchange,提问作者Mauro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 21:24:03