Danilo
Danilo

Reputation: 2036

mysqli perform multiple queries into foreach

I wrote the following code to store data on my mysql db. The problem is that the insert or the update query is executed once, only the first cycle. I tryed to find solution searching on stackoverflow and google but without success. Anyone could help me.

foreach($data as $val){

            $result = $con->query('SELECT id FROM mytable where name = "'.$val'"');
            $row = $result->fetch_row();

            if(isset($row[0]) ) $id =  $row[0];

            if(!isset($id)) {
                 $queryInsert = "INSERT INTO mytable bla bla );";
                 $result = $con->query($queryInsert);
                 $id = $con->insert_id;
            }
            else {
                 $queryUpdate = "UPDATE mytable bla bla";
                 $result = $con->query($queryUpdate);
            }

            //other code and queries ...

        }

Upvotes: 0

Views: 476

Answers (1)

Mihai Iorga
Mihai Iorga

Reputation: 39704

You could check num_rows and then insert or update

foreach($data as $val){
    $result = $con->query('SELECT id FROM mytable where name = "'.$val.'"');
    $num = $result->num_rows;

    if($num){ //it exists -> update

        $queryUpdate = "UPDATE mytable SET bla bla";
        $resultUpdate = $con->query($queryUpdate);
        $row = $result->fetch_assoc();
        $id = $row['id'];

    } else { //it doesnt exist insert

        $queryInsert = "INSERT INTO mytable VALUES ( bla bla );";
        $resultInsert = $con->query($queryInsert);
        $id = $resultInsert->insert_id;
    }
}

Upvotes: 1

Related Questions