开发者

I want to search the database if the table contains the data already, if not then insert it

I'm using MySQLi prepared statements to do this because the data is coming from other sources. Here's my code it do开发者_运维技巧ens't work man. I don't understand why I need to do $stmt->store_result() in order to run num_rows().. Because If I don't run store_result, I would get an error:

Fatal error: Call to a member function bind_param() on a non-object

foreach($this->contents as $key => $dealer) {
        foreach($dealer as $deals) {
               $stmt = $mysqli->prepare("SELECT id, name FROM company WHERE name = ? LIMIT 1");
               $stmt->bind_param("s", $deals['company']);
               $stmt->execute();
               $stmt->store_result();

               if($stmt->num_rows() > 0) {
                     $companyid = // I don't know how to get the id from the query
               } else {
                     $stmt->prepare("INSERT INTO company (name) VALUES (?)");
                     $stmt->bind_param("s", $deals['company']);
                     $stmt->execute();
               }
               $stmt->close();
        }
}

Basically I want the code to check if the company already exists in the company table, then after checking it, if the company exists then I need to record the id of the company so i can use it in my other queries, but if it doesn't exists then I need to record the company name then get the id so i can use it in my other queries.


To get your $companyId you need to do $stmt->bind_result() and $stmt->fetch(). Docs on fetch()

if($stmt->num_rows() > 0) {
  // To get your companyId
  $stmt->bind_result($companyId);
  $stmt->fetch()

  // Now $companyId has the value from id in the database
} else {
  // Do your insert statement, etc...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜