简体   繁体   English

如何在php中使用内连接将值从下拉菜单发送到数据库到两个不同的表

[英]How to use inner join in php to send values from dropdown menu to database to two different tables

So I made a page where you can create a post and add a 'auteur', but the 'auteur' needs to get inserted into the database with the 'auteur_id' and the name of the 'auteur'.因此,我创建了一个页面,您可以在其中创建帖子并添加“auteur”,但“auteur”需要使用“auteur_id”和“auteur”的名称插入到数据库中。 So when you create a post, you can choose between three 'auteurs' and it has to be inserted into the database using inner join, and get the right 'auteur_id' that belongs to the chosen 'auteur', but how can I do this?因此,当您创建帖子时,您可以在三个“auteurs”之间进行选择,并且必须使用内部联接将其插入到数据库中,并获得属于所选“auteur”的正确“auteur_id”,但是我该怎么做? This is my database export.sql:这是我的数据库 export.sql:

DROP DATABASE IF EXISTS foodblog;

CREATE DATABASE foodblog;

USE foodblog;

CREATE TABLE auteurs (
    id int(11) AUTO_INCREMENT,
    auteur varchar(255),
    PRIMARY KEY (id)
);

CREATE TABLE posts (
    id int(11) AUTO_INCREMENT,
    titel varchar(255),
    datum DATETIME DEFAULT current_timestamp(),
    img_url varchar(255),
    inhoud text,
    auteur_id int(11),
    PRIMARY KEY (id),
    FOREIGN KEY (auteur_id) REFERENCES auteurs(id)
);

INSERT INTO auteurs (auteur)
VALUES ('Mounir Toub');

INSERT INTO auteurs (auteur)
VALUES ('Miljuschka');

INSERT INTO auteurs (auteur)
VALUES ('Wim Ballieu');

INSERT INTO posts (titel, datum, img_url, inhoud)
VALUES
    ('Pindakaas', '2020:06:18 13:25:00', 'https://i.ibb.co/C0Lb7R1/pindakaas.jpg','Verwarm de oven voor op 180 °C. Verdeel de pinda’s over een met bakpapier beklede bakplaat en rooster in ca. 8 min. lichtbruin. Schep regelmatig om. Maal de warme pinda’s in de keukenmachine in 4 min. tot een grove, dikke pindakaas. Schep de rand van de kom regelmatig schoon met een spatel. Voeg het zout, de olie en honing toe en maal nog 1 min. tot een gladde pindakaas. Schep in een pot en sluit af.
        variatietip: Houd je van pindakaas met een smaakje? Voeg dan na de honing 1 el sambal badjak, 1 tl gemalen kaneel of 1 el fijngehakte pure chocolade toe. bewaartip: Je kunt de pindakaas 3 weken in de koelkast bewaren.'),
    ('Baklava', '2020:03:11 10:28:00', 'https://i.ibb.co/ZWVRdPT/baklava.jpg','Voorbereiding

    Verwarm de oven voor op 190 °C. Vet de bakvorm in met roomboter.
    Smelt de roomboter in een pannetje. Snijd het baklavadeeg op dezelfde breedte als de bakvorm en bewaar het in een schone droge keukendoek om uitdrogen te voorkomen. Verwarm in een pan 300 gr honing met 20 ml oranjebloesemwater en houd dit mengsel warm. Roer in een mengkom de gezouten roomboter, 500 g gemalen walnoten, de rest van de honing en het oranjebloesemwater en de kaneel door elkaar. Verdeel het mengsel in zeven gelijke porties (van circa 90 g).

    Bereiding
    Bestrijk een vel baklavadeeg met gesmolten roomboter. Leg er een tweede vel op en bestrijk dat ook. Neem één portie van het walnotenmengsel en verdeel dat onderaan over het baklavadeeg. Rol op tot een staaf, leg deze in de bakvorm en bestrijk met gesmolten roomboter. Maak de rest van de staven op dezelfde manier.
    Snijd elke staaf met een scherp mes meteen in zessen. Bak de baklava in circa 25 minuten goudbruin en krokant in de oven.
    Neem de bakvorm uit de oven en verdeel de warme honing over de baklava. Garneer meteen met de rest van de fijngemalen walnoten. Laat de baklava minimaal 3 uur afkoelen voordat je ervan gaat genieten.')

The code:编码:

<html>

    <head>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>

    <body>
        <div class="container">

            <div id="header">
                <h1>Nieuwe post</h1>
                <a href="index.php"><button>Alle posts</button></a>
            </div>

        <?php
            $host = 'localhost';
            $username = 'root';
            $password = '';
            $dbname = 'foodblog';
            $dsn = 'mysql:host=' . $host . ';dbname=' . $dbname;
            
            try {
                $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
                // set the PDO error mode to exception
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch (PDOException $e) {
                echo "Connection failed: " . $e->getMessage();
            }
            
        try {
            if (isset($_POST["submit"])) {
                $titel = $_POST['titel'];
                $img = $_POST['img_url'];
                $inhoud = $_POST['inhoud'];
                $auteur = $_POST['auteur'];
                $sql = "INSERT INTO posts (titel, img_url, inhoud, auteur) 
                VALUES ('$titel', '$img', '$inhoud', '$auteur')
                FROM posts INNER JOIN auteurs ON posts.auteur_id = auteurs.id";
                $conn->exec($sql);
            } else {
        ?>
                <form action="new_post.php" method="post">
    Titel:<br/> <input type="text" name="titel"><br/><br/>
    Auteurs:<br>
    <select name='auteur'>
    <option>Mounir Toub</option>
    <option>Miljuschka</option>
    <option>Wim Ballieu</option>
    </select>
    <br><br>
    URL afbeelding:<br/> <input type="text" name="img_url"><br/><br/>
    Inhoud:<br/> <textarea name="inhoud" rows="10" cols="100"></textarea>
    <br/><br/>
    <input type="submit" name="submit" value="Publiceer">
</form>
        <?php
            }
        } catch(error) {
            console.error(error);
        }
        ?>

    </body>
</html>

Maybe this query could help?也许这个查询有帮助?

$sql = "INSERT INTO posts (titel, img_url, inhoud, auteur) 
        SELECT '$titel', '$img', '$inhoud', auteur_id
        FROM auteurs
        WHERE auteur='$auteur'";

To "break things down", a SELECT is used to create the data set that the INSERT needs.为了“分解”,使用 SELECT 来创建 INSERT 需要的数据集。 Unless one starts to complicate things the SELECT will be fairly similar to a stand-alone query, it'll only "see" the tables mentioned in the FROM, or JOINs if you'd add some of those.除非开始使事情变得复杂,否则 SELECT 将与独立查询非常相似,否则它只会“看到” FROM 中提到的表,或者如果您添加其中的一些,则它会“看到” JOIN 中的表。 Therefor you don't need to write WHERE auteurs.auteur=... .因此你不需要写WHERE auteurs.auteur=... Adding the table name is allowed, though, and might add some extra clarity.但是,允许添加表名,并且可能会增加一些额外的清晰度。

Big fat note: As others have already said, you should not use a carbon copy of this, because the data from the user goes straight into your SQL query which leaves it wide open to SQL injection.大胖子注:正如其他人已经说过,你应该使用这个翻版,因为从用户的数据直接进入您的SQL查询它的叶子是敞开的SQL注入。 Use parametrized queries.使用参数化查询。 Please.请。

The reason I didn't add it in the answer was that this question isn't specifically about security, but a way to insert data from one table into another.我没有在答案中添加它的原因是这个问题不是专门关于安全性的,而是一种将数据从一个表插入另一个表的方法。 (Right?) (对?)

Also, you might want to consider using the auteur ids in your elements, like:此外,您可能需要考虑在元素中使用 auteur id,例如:

<option value="1">Mounir Toub</option>

That way you get the id directly for the insert, and you won't have to worry about different auteurs having the same name.这样你就可以直接获得插入的 id,你就不必担心不同的 auteur 有相同的名字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM