我编写了以下代码来存储我的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 ...
}
答案 0 :(得分: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;
}
}