Joe
Joe

Reputation: 3

Error in mysqli->prepare with insert statement

I'm trying to figure out why my first prepare statement works just fine but my second one doesn't. The actual INSERT INTO syntax looks correct and works when I substitute numbers and place it in a mysql console, but the prepare statement returns false.

Just to clear away the simple questions; $db_table_prefix == "uc_" and all variables are initialized. Also, the first statement sets $results == 0 (EDIT: this was my mistake, it's really 0, not 1).

global $mysqli,$db_table_prefix;

$stmt = $mysqli->prepare("SELECT COUNT(id) FROM ".$db_table_prefix."attempts WHERE ((exp_m = ?) AND (exp_n = ?) AND (max_base <= ?))");
$stmt->bind_param("iii", $m, $n, $this->max_base);
$stmt->execute();
$stmt->bind_result($results);
$stmt->fetch();

if ($results < 1)
{ 
  $stmt = $mysqli->prepare("INSERT INTO ".$db_table_prefix."attempts (exp_m, exp_n, base_x, max_base) VALUES (?,?,?,?)");
  $stmt->bind_param("iiii", $m, $n, $x, $this->max_base);

  .....
}

I've included the table structure, just in case that's the issue.

mysql> describe uc_attempts;
+----------+---------------------+------+-----+---------+----------------+
| Field    | Type                | Null | Key | Default | Extra          |
+----------+---------------------+------+-----+---------+----------------+
| exp_m    | bigint(20) unsigned | NO   |     | NULL    |                |
| exp_n    | bigint(20) unsigned | NO   |     | NULL    |                |
| base_x   | bigint(20) unsigned | YES  |     | NULL    |                |
| max_base | bigint(20) unsigned | NO   |     | NULL    |                |
| id       | int(11)             | NO   | PRI | NULL    | auto_increment |
+----------+---------------------+------+-----+---------+----------------+

I'm sure I'm just missing something simple, but after a few days of staring at the code, I needed to ask. Thanks in advance for the help. Please let me know if there is any other information I should include.

Upvotes: 0

Views: 247

Answers (1)

Sumurai8
Sumurai8

Reputation: 20737

You forgot to close the first resource. I believe it can't open a second prepared statement if the first one isn't closed. I think $mysqli->prepare( ... ); will then return false and obviously false->bind_param( ... ); does not exist ;-) causing your Fatal error: Call to a member function bind_param() on a non-object-error.

global $mysqli,$db_table_prefix;

$stmt = $mysqli->prepare("SELECT COUNT(id) FROM ".$db_table_prefix."attempts WHERE ((exp_m = ?) AND (exp_n = ?) AND (max_base <= ?))");
$stmt->bind_param("iii", $m, $n, $this->max_base);
$stmt->execute();
$stmt->bind_result($results);
$stmt->fetch();
$stmt->close(); //<-- this is the problem

if ($results < 1)
{ 
  $stmt = $mysqli->prepare("INSERT INTO ".$db_table_prefix."attempts (exp_m, exp_n, base_x, max_base) VALUES (?,?,?,?)");
  $stmt->bind_param("iiii", $m, $n, $x, $this->max_base);

  .....
}

Upvotes: 1

Related Questions