【问题标题】:I want to search the database if the table contains the data already, if not then insert it如果表已经包含数据,我想搜索数据库,如果没有,则插入它
【发布时间】:2011-03-22 13:37:05
【问题描述】:

我正在使用 MySQLi 准备好的语句来执行此操作,因为数据来自其他来源。 这是我的代码,它不起作用。我不明白为什么我需要做$stmt->store_result() 才能运行 num_rows().. 因为如果我不运行 store_result,我会得到一个错误:

致命错误:在非对象上调用成员函数 bind_param()

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();
        }
}

基本上我希望代码检查公司表中是否已经存在,然后在检查之后,如果公司存在,那么我需要记录公司的 ID,以便我可以在其他查​​询中使用它,但是如果它不存在,那么我需要记录公司名称然后获取 ID,以便我可以在其他查​​询中使用它。

【问题讨论】:

标签: php mysqli prepared-statement


【解决方案1】:

要获得您的$companyId,您需要执行$stmt->bind_result()$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...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    相关资源
    最近更新 更多