简体   繁体   中英

Trouble understanding how to send an array to a mySQL datatable

I just dove into using phpmyAdmin and mySQL today and I'm having some trouble understanding how to send an array to a table using a for loop. The $tid is a set number that changes transaction to transaction. $wineFirstNames and $wineLastNames are both arrays.

for( i=1;i <= $wineQty; i++) {
    $wineTastingTable = "INSERT INTO wineTastingTable (transactionID, wineFirstName, wineLastName) VALUES ('$tid','$wineFirstNames[$i]','$wineLastNames[$i]')"
    if (!mysqli_query($con,$wineTastingTable)) {
       die('Error: ' . mysqli_error($con));
       }

Any help is greatly appreciated!

try this i think you forgot adding $ in for loop

    for( $i=1;$i <= $wineQty; $i++) {
                $wineTastingTable = "INSERT INTO wineTastingTable (transactionID, wineFirstName, wineLastName) VALUES ('".$tid."','".$wineFirstNames[$i]."','".$wineLastNames[$i]."')";
                if (!mysqli_query($con,$wineTastingTable)) {
                    die('Error: ' . mysqli_error($con));
                }
}

As other answers have mentioned, all variables must be declared with $ to be interpreted, otherwise (in your context) it'll be interpreted as a string. You may always want to try a foreach loop, like so:

   foreach ($array as $item){
       $query="INSERT INTO wines (id, field1, field2) VALUES ($item[0], $item[1], $item[2])";
       MySQLi_query($conn,$query) or die(mysqli_error());
   }

This is assuming a multi-dimensional array structure, but it looks like (from your post) that's what you're working with.

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