views:

21

answers:

2

So here's the codeblock:

        $query = "UPDATE users SET ?=? WHERE ?=?";

        $type = "s";
        $type .= substr(gettype($valname), 0, 1);
        $type .= 'i';

        if ( $smtp = $this->conn->prepare($query) )
        {
            $smtp->bind_param($type, $colname, $valname, 'id', 40);
            $smtp->execute();
            $smtp->close();

        }else
        {
            return $this->conn->error;

        }

For some reason it refuses to bind the parameters, and it gives me this error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?=? WHERE ?=?' at line 1

If i add backticks ( ` ) or singlequotes ( ' ) around the questionmarks i get this error instead:

Unknown column '?' in 'where clause'

Any ideas what's gone wrong? I've been sitting here for hours playing with it, god it's frustrating!!

Thanks a bunch!

+2  A: 

I do not think you can define the column dynamically in a prepared statement, only values, as these are escaped etc. You will need to put the column name in the $query string, if it comes from an unknown source make sure you filter it and validate it.

Brad F Jacobs
Ahh, alright. You may be right, but i got another error now: Fatal error: Cannot pass parameter 3 by reference in blablbla...., the query looks like this now: "UPDATE users SET $colname=? WHERE id=?", looks good? I also removed the column names from the bind_param function: ($type, $valname, 40).
Nike
I forgot to say i also fixed the $type parameter. Still not working...
Nike
Got it! I moved the ID to a seperate string and then linked the string in the function instead. Seems to be working! :)
Nike
+2  A: 

As far as I know, you can only use ? placeholders for the condition, not for table/field names.

See: http://php.net/manual/en/pdo.prepared-statements.php

froadie
Ahh, alright. You may be right, but i got another error now: Fatal error: Cannot pass parameter 3 by reference in blablbla...., the query looks like this now: "UPDATE users SET $colname=? WHERE id=?", looks good? I also removed the column names from the bind_param function: ($type, $valname, 40).
Nike
I forgot to say i also fixed the $type parameter. Still not working...
Nike