Igor Unger Igor Unger - 11 days ago 6
PHP Question

PDO bind Parameter

I'm getting involved in PDO now and theres one thing I try to understand:

If I try:

$var = "bing";
$sth-> bindParam(":parameter",$var);
$sth-> execute ();


I get no results.

But if I try:

$sth-> bindParam(":parameter",$var);
$var = "bing";
$sth-> execute ();


I do. WHY???

Answer

It should work both ways.

Double-check your premises, create a minimal working example that clearly demonstrates the problem. E.g.

$sth = $pdo->prepare("SELECT :parameter");
$var = "bing";
$sth->bindParam(":parameter",$var);
$sth->execute();
var_dump($sth->fetchColumn());

$sth = $pdo->prepare("SELECT :parameter");
$sth->bindParam(":parameter",$var2);
$var2 = "bong";
$sth->execute();
var_dump($sth->fetchColumn());

Most of time, in the process of creation, you will find that simple typo which caused your mistake.

P.S. Either way, better make it just

$sth = $pdo->prepare("SELECT ?");
$var = "bing";
$sth->execute([$var]);
var_dump($sth->fetchColumn());
Comments