【问题标题】:mysqli perform multiple queries into foreachmysqli 对 foreach 执行多个查询
【发布时间】:2013-07-11 13:09:13
【问题描述】:

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

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

        }

【问题讨论】:

  • 使用mysql功能insert on duplicate key update

标签: php mysql mysqli


【解决方案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;
    }
}

【讨论】:

  • 如果有更新,我还需要保存 $id 变量,因为我必须将此值存储在另一个表中。问题是插入或更新只在第一个周期执行。
猜你喜欢
  • 2017-07-22
  • 2019-02-07
  • 1970-01-01
  • 2013-09-19
  • 1970-01-01
  • 1970-01-01
  • 2015-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多