Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Fatal error: Call to a member function bind_param() [duplicate]

Tags:

php

mysql

I've been pulling my hair out on this MySQL query.

Let's say I have this:

    $add = "INSERT INTO books (title) VALUES(?)";
    if ($stmt = $mysqli->prepare($add)) {

        $arr = array($title);

        foreach ($arr as $value) {
            echo var_dump($value);
        }

        $stmt->bind_param("s", $title);

With that foreach -> var_dump :

string 'Medieval Times (History)' (length=24)
int 1422843281
int 1420844341
string '127.0.0.1' (length=9)
string '[email protected]' (length=22)
string '' (length=0)
int 1420844805
int 6
int 3
int 1
int 0
int 0
int 1
int 1
int 1
int 1

Well, it stops when it hits this line and I get this error:

Fatal error: Call to a member function bind_param() on a non-object in C:\wamp\www\books\dashboard.php on line 386

With line 386: $stmt->bind_param ...

So, I know I am importing 16 variables yet ... I get this error. Argh.

like image 613
Zeng Cheng Avatar asked Jul 05 '26 03:07

Zeng Cheng


2 Answers

TL\DR

Your query is failing to prepare(). You need to figure out where, how and why. Look at the last code block of this answer and let us know what the error is.


I'll start with the query. You're trying to access a MySQL reserved word Source (See #684). You need to wrap those in backticks like this:

$add = "INSERT INTO books (title, edited, created, ip,".
    " email_to, twitter, last_taken, questions_total, responses, ".
    "show_progress, need_correct, go_back, state, send_stats, ".
    "show_number, imported) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ".
    "?, ?, ?, ?, ?, ?, ?)";

Now, you're instantiating the variable $stmt within the if block but then trying to bind it outside of that block. You'll need to change this:

if ($stmt = $mysqli->prepare($add)) {
....
}
$stmt->bind_param(....);

To this:

if ($stmt = $mysqli->prepare($add)) {
....
$stmt->bind_param(....);
}

Also, make sure your query is actually preparing correctly:

if ($stmt = $mysqli->prepare($add)) {

    $stmt->bind_param("siisssiiiiiiiiii", $title, $edited, $created, $ip, $email_to, $twitter, $last_taken, $questions_total, $responses, $show_progress, $need_correct, $go_back, $state, $send_stats, $show_number, $importedVal);

    // execute it and all...
} else {
    die("Errormessage: ". $mysqli->error);
}

Then let us know what turns up.

like image 122
Darren Avatar answered Jul 06 '26 20:07

Darren


Edited: try this

if ($stmt = $mysqli->prepare($add)) {

    $stmt->bind_param($arr);
}
else {
    printf("Errormessage: %s\n", $mysqli->error);
}

http://php.net/manual/en/mysqli-stmt.bind-param.php

like image 20
mehany Avatar answered Jul 06 '26 20:07

mehany



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!