i wrote following code store data on mysql db. problem insert or update query executed once, first cycle. tryed find solution searching on stackoverflow , google without success. me.
foreach($data $val){ $result = $con->query('select id mytable name = "'.$val'"'); $row = $result->fetch_row(); if(isset($row[0]) ) $id = $row[0]; if(!isset($id)) { $queryinsert = "insert mytable bla bla );"; $result = $con->query($queryinsert); $id = $con->insert_id; } else { $queryupdate = "update mytable bla bla"; $result = $con->query($queryupdate); } //other code , queries ... }
you check num_rows
, insert or update
foreach($data $val){ $result = $con->query('select id mytable 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 mytable values ( bla bla );"; $resultinsert = $con->query($queryinsert); $id = $resultinsert->insert_id; } }
Comments
Post a Comment