0

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'. 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? This is my database 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>
Mauro
  • 342
  • 3
  • 10
  • Do **not**, **never**, **never ever** post images of tables. Post the `CREATE` and `INSERT` statements as **text**. – sticky bit Oct 27 '21 at 08:55
  • (Possible) side note: Do not use string interpolation or concatenation to get values into SQL queries. That's error prone and might make your program vulnerable to SQL injection attacks. Use parameterized queries. See ["How to include a PHP variable inside a MySQL statement"](https://stackoverflow.com/questions/7537377/how-to-include-a-php-variable-inside-a-mysql-statement) and ["How can I prevent SQL injection in PHP?"](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – sticky bit Oct 27 '21 at 08:56
  • Which dbms are you using? (Some strange SQL above.) – jarlh Oct 27 '21 at 08:57

1 Answers1

0

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. 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. Therefor you don't need to write 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. 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:

<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.

Torbjörn Stabo
  • 769
  • 4
  • 7