Home > Net >  PHP: Cannot execute a SQL insert query via script
PHP: Cannot execute a SQL insert query via script

Time:10-25

I am trying to get my php function to insert data into my Database. This is the php part:

//Adds entries for a order
function PlaceOrder($customerId, $idArray, $cost, $db) {
    $nextOrderId=0;
    $sql=
        'SELECT AUTO_INCREMENT AS next
            FROM information_schema.TABLES
        WHERE TABLE_SCHEMA = "krautundrueben" AND TABLE_NAME = "BESTELLUNG"'
    ;
    $sql=contactDb($db, $sql);

    while($row = $sql->fetch_assoc()){
        $nextOrderId=$row["next"];
    }

    $sql='INSERT INTO BESTELLUNG (KUNDENNR, BESTELLDATUM, RECHNUNGSBETRAG) VALUES ('.$customerId.', '.date('Y-m-d').', '.$cost.');';
    
    foreach ($idArray as $key => $value) {
        $sql.='INSERT INTO BESTELLUNGZUTAT(BESTELLNR, ZUTATENNR, MENGE) VALUES ('.$nextOrderId.', '.$key.', '.$value.');';
    }

    echo $sql;
    contactDb($db, $sql);
}

Here is our dbConnect.php:

<?php
$db = mysqli_connect("localhost","root","","krautundrueben");

if(!$db)
{
    die("Connection failed: " . mysqli_connect_error());
}

function contactDb($db, $command){

    $send = mysqli_query($db, $command);

    return $send;
}

function closeDb($db) {
    mysqli_close($db);
}

?>

And here is the SQL command that results from this: INSERT INTO BESTELLUNG (KUNDENNR, BESTELLDATUM, RECHNUNGSBETRAG) VALUES (2008, 2021-10-25, 1.2); INSERT INTO BESTELLUNGZUTAT(BESTELLNR, ZUTATENNR, MENGE) VALUES (17, 7043, 6);

The weird thing is: the "17" is the result from the first "contactDb()" so a connection is established and working. If I then copy & paste the SQL command that my function created directly into phpmyadmin, it works just fine. But for some reason it does not via php and just keeps returning null...

PS: We are aware of how insecure our db and our queries are. Since this is a school project with a small time-window, it doesnt matter

  • Related