donglian2106 2011-03-22 13:37
浏览 66
已采纳

我想搜索数据库,如果表已包含数据,如果没有,则插入它

I'm using MySQLi prepared statements to do this because the data is coming from other sources. Here's my code it doens'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.

Please help me.

  • 写回答

1条回答 默认 最新

  • douji1999 2011-03-22 13:52
    关注

    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...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效