简体   繁体   中英

Selecting data from two tables, inserting it into new table? (SQL / PHP)

For days I've been trying the following: I have a HTML form. After receiving the data (MENGE / PRODUKT / LIEFERANT) I want to insert the data into the table "bestellung". For this purpose, I need two different data points from two different tables: the Waren_ID from the WARE table and the kunde_lieferant_ID from the kunde_lieferant table.

Every time I try this, I get a new error in whatever form (syntax, ...). I've read dozens of Stack Overflow posts, but none helped me out. It would be great if someone could give me a hint :-)

<?php
$server="localhost";
$username="xy";
$passwort="xy";
$database="xy";
$conn=mysqli_connect($server, $username, $passwort, $database)
or die ("Fehler im System");


if (!empty($_POST["Lieferant"]) AND !empty ($_POST["Produkt"]) AND !empty ($_POST["Menge"]))
{

$Menge = $_POST ["Menge"];
$Produkt = $_POST["Produkt"];
$Lieferant = $_POST ["Lieferant"];


$sql="SELECT Waren_ID FROM ware WHERE Name='$Produkt'";
$speichern = mysqli_query($conn, $sql);
$rs = mysqli_fetch_array($speichern);
$Waren_ID=$rs['Waren_ID'];

$abfrage="SELECT kunde_lieferant_ID FROM kunde_lieferant WHERE Name='$Lieferant'";
$result = mysqli_query($conn, $abfrage);
$ts = mysqli_fetch_array($result);
$kunde_lieferant_ID=$ts['kunde_lieferant_ID'];


$final="INSERT INTO bestellung (Menge, Waren_ID, kunde_lieferant_ID) values ($Menge, $Waren_ID, $kunde_lieferant_ID)";
$ende=mysqli_query($conn, $final)
or die ("Fehlgeschlagen: SQL-Error:" . mysqli_error($conn));
}

mysqli_close($conn);
?>

Add MYSQLI_ASSOC as a second argument to mysqli_fetch_array() to use the key name instead of the integer index number:

$rs = mysqli_fetch_array($speichern); becomes $rs = mysqli_fetch_array($speichern, MYSQLI_ASSOC);

and

$ts = mysqli_fetch_array($result); becomes $ts = mysqli_fetch_array($result, MYSQLI_ASSOC);

You may also use $rs = mysqli_fetch_assoc($speichern); and $rs = mysqli_fetch_assoc($speichern); to access the associative array by key name instead of index.

One potential problem in your insert statement is that you are not single-quoting the values that your are passing : to MySQL, this means that they are all numeric (but is « Menge » numeric for example ?).

To avoid this and also prevent your code from SQL injection, you probably should use parameterized queries.

By looking more globally at your code, I think that you should be able to achieve what you want in a single INSERT ...SELECT statement, like :

INSERT INTO bestellung
SELECT
    :menge, 
    w.Waren_ID, 
    k.kunde_lieferant_ID
FROM
    ware w
    INNER JOIN kunde_lieferant k
        ON k.Name = :lieferant
WHERE w.Name = :produkt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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