0

我编写了以下代码来将数据存储在我的 mysql 数据库中。问题是插入或更新查询执行一次,只有第一个循环。我试图在 stackoverflow 和谷歌上寻找解决方案,但没有成功。任何人都可以帮助我。

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 ...

        }
4

1 回答 1

1

您可以检查num_rows然后插入或更新

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;
    }
}
于 2013-07-11T13:13:14.650 回答