Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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);

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"
));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top