1

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Kevin Lee
  • 1,079
  • 6
  • 17
  • 34

1 Answers1

1

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...
}
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390