Home » Php » mysql – PHP SQL Update table with foreach loop values

mysql – PHP SQL Update table with foreach loop values

Posted by: admin February 25, 2020 Leave a comment

Questions:

Hi there i need some help.

i need help updating a row in a data with a foreach loop.

i am using the following at the moment but it only prints 1 of the values.

Checking if there are values in the Test1 form run through foreach and then check if they are in the db

if(!empty($_POST["Test1"])){
$tests = $_POST["Test1"];

foreach ($tests as $key =>$value){

    $test[] = $value;

    $res = $connect->query("SELECT ID FROM tbltest where testname = '$value'");

create an array from the result

$testIDs = array();
    $testIDs = mysqli_fetch_assoc($res);

another foreach to check the ID in the database to use in a different table

if(is_array($testIDs)){
        foreach ($testIDs as $key=>$values){


            $testID[] = $values;

insert values into different table

$sql2 = "INSERT INTO tbltesting (ID, testID)
    VALUES ('$tickets', '$values');";

update initial insert request

$sqlUpdate = "UPDATE tblmaintest SET tests = '$value' WHERE TicketID = '$tickets'";
mysqli_query($connect, $sqlUpdate);

i would like the update statement to update all the values in the array but it is only updates to 1 value, not all that are in the array, works fine with only one value, but does not print more than one into the database.

full code

if(!empty($_POST["Test1"])){
$tests = $_POST["Test1"];

foreach ($tests as $key =>$value){

    $test[] = $value;

    $res = $connect->query("SELECT ID FROM tbltest where testname = '$value'");


    $testIDs = array();
    $testIDs = mysqli_fetch_assoc($res);

    if(is_array($testIDs)){
        foreach ($testIDs as $key=>$values){


            $testID[] = $values;



$sql2 = "INSERT INTO tbltesting (ID, testID)
    VALUES ('$tickets', '$values');";

mysqli_query($connect, $sql2);

$sqlUpdate = "UPDATE tblmaintest SET tests = '".$test."' WHERE TicketID = '$tickets'";
mysqli_query($connect, $sqlUpdate);


        }

    }
How to&Answers: