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
  • 21,838
  • 18
  • 57
  • 107
Kevin Lee
  • 1,051
  • 4
  • 15
  • 31

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
  • 253,311
  • 39
  • 421
  • 371