PHP PDO bindValue() fails

1.1k views Asked by At

I'm new to PHP's PDO and got a little problem with a function of my database class:

function set($query, $args = array())   {
try {
    $query = $this->rs->prepare($query);

    $x = 1;
    foreach($args as $arg)  {
        $query -> bindValue($x, $arg);
        $x++;
    }

    $query->execute($args);
}
catch(PDOException $e)  {
    print_r($e);
}
}

It's supposed to automatically bind the "?" in the query to their value in the array $args.

Example:

$db -> set("INSERT INTO messages(date,regard,sender,to,msg) VALUES('?','?','?','?','?')", array(
    "bla",
    "bla2",
    "bla3",
    "bla4",
    "bla4"
));

But it doesn't work. In the database, all cols contains those stupid question marks. Where is the problem?

3

There are 3 answers

1
user268396 On BEST ANSWER

You have quoted your question marks, so the database sees literal strings containing just a single ?, instead of the placeholder marker (question mark). Simply use the question mark without quoting it: the system automatically uses the correct syntax for the relevant data types.

0
Maarkoize On

Try to remove the quotation marks from your query:

$db -> set("INSERT INTO messages(date,regard,sender,to,msg) VALUES(?,?,?,?,?)", array(
    "bla",
    "bla2",
    "bla3",
    "bla4",
    "bla4"
));

If you are only input strings, then you can force this with a third parameter in bind_value PDO::PARAM_STR

$query -> bindValue($x, $arg, PDO::PARAM_STR);
0
Krish R On

It should be like with out quotes '?' i.e it should be ?

$db -> set("INSERT INTO messages(date,regard,sender,to,msg) VALUES(?,?,?,?,?)", array(
"bla",
"bla2",
"bla3",
"bla4",
"bla4"
));