0

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???

2
  • Did you ->prepare your SQL statement? Commented Sep 21, 2016 at 11:09
  • @Martin Yes, I did. @ Ryan I like the colon writing, because it I think its better to read. Commented Sep 21, 2016 at 17:21

1 Answer 1

2

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());
Sign up to request clarification or add additional context in comments.

11 Comments

Thank you, for your answer. I tried it again and everything worked perfectly well. I don't know, where my problem was the last time. It never gets boring! ;-)
Why is just. $var = "bing"; $sth->execute([$var]); better?
You shouldn't be concerned in "faster" things at all.
Nope, optimizing SQL queries is a good thing. But still, only if it's not premature optimization out of nowhere. Blunt optimization (like adding useless indexes) will lead to opposite results as well.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.