PDO prepared statements

Hello, i am trying to run a query based on user input. I’m using prepared statements, but something is wrong in my code, and i just cannot understand what. My code is as follows:

[php]
function sortByClass(String $class) {

    $candidates=array();

    $stmt = $this->db->prepare("SELECT lastName, surName, class, phone, FROM people WHERE class =:class ORDER BY lastName");
    $stmt->bindParam(':class', $class, PDO::PARAM_INT);
    $stmt->execute();

    while ($number= $stmt->fetchObject('Candidate')) {

        $candidates[] = "$number";
    }
    return $candidates;
}

[/php]

I notice that if i in my query replace WHERE class =:class with WHERE class = ‘real_class_name’, i get an array returned with the desired results. So i believe the problem lies with the prepared statement…somewhere. (I translated this into english, i’m aware that i should not use the name “class” as variable, the naming is different in my code)

The problem lies here:
[php]
$stmt->bindParam(’:class’, $class, PDO::PARAM_INT);
[/php]

If you have a look here:

PDO::PARAM_BOOL (integer) Represents a boolean data type. PDO::PARAM_NULL (integer) Represents the SQL NULL data type. PDO::PARAM_INT (integer) Represents the SQL INTEGER data type. PDO::PARAM_STR (integer) Represents the SQL CHAR, VARCHAR, or other string data type. PDO::PARAM_LOB (integer) Represents the SQL large object data type. PDO::PARAM_STMT (integer) Represents a recordset type. Not currently supported by any drivers. PDO::PARAM_INPUT_OUTPUT (integer) Specifies that the parameter is an INOUT parameter for a stored procedure. You must bitwise-OR this value with an explicit PDO::PARAM_* data type.
You will notice that you are telling the statement that the class is an integer, or a number, not a name.

I’m not sure what you are using for that variable, but from your post, I’m assuming a string (as that is the type hinting in the function argument). So, you should be using PDO::PARAM_STR

Sponsor our Newsletter | Privacy Policy | Terms of Service