jcobo1
jcobo1

Reputation: 1180

php bind parameters on SQL statement is not working

I'm trying to do a select on php but I'm having problems passing bind parameters to a standard sql statement. I already have lost all my day with this and I can't find any solution. I have a sql statement and a parameter (this part is changing constantly)

Here I have my sql statement and the execution:

$mysqli=getDB();
    $stmt = $mysqli->prepare('SELECT nom from noms where id=?'); // cambiar select 
    $sql->bind_param($id);
    $result = $mysqli->query($sql);
    $results = array();
    while($row = mysqli_fetch_array($result)){
        $results[] = array( // modificar el que passa dintre del bucle
            'nom' => $row['nom']
         );
    }

   echo json_encode($results);

Here is how I connect with database (getDB()):

function getDB() {
    // Credencials
    $servername = "server";
    $username = "user";
    $password = "pswwd";
    $dbname = "database";


    $mysqli = new mysqli($servername, $username, $password, $dbname);
    if ($mysqli->connect_errno) {
        echo "Error al connectar: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }

    return $mysqli;

}

All this is actually a web service function, when I call it I get an 500 message error. I need to run the statement changing the $id value (this parameters come from outside). I'm only receiving a 500 error status from the JS console but I don't see any error message.

Edit:

I did a few changes on the statement and execution:

$mysqli=getDB();
        $stmt = $mysqli->prepare('SELECT nom from noms where id=?'); // cambiar select 
        $stmt ->bind_param($id);
        $result = $mysqli->query($stmt );
        $results = array();
        while($row = mysqli_fetch_array($result)){
            $results[] = array( // modificar el que passa dintre del bucle
                'nom' => $row['nom']
             );
        }

       echo json_encode($results);

The log still showing the same message: PHP Fatal error: Call to a member function bind_param() on a non-object

Upvotes: 0

Views: 803

Answers (1)

Marc B
Marc B

Reputation: 360842

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

The syntax is

$stmt->bind_param('types', $var1, $var2, etc....)

You only provided the $var1 portion, and forgot the types. You need to tell mysqli what TYPE your parameter is, e.g.

$stmt->bind_param('i', $id);
                  ^^^---missing in your version

And note that ANYtime you get a 500, you immediately go look at your webserver's error log for actual details. What you see in your browser is deliberately vague, since 500 errors can reveal core/configuration details that should never become public.

Upvotes: 1

Related Questions