Why do prepared statements to be stored?

I’m assuming you have to because all the examples in the book are stored.

say for example

$sql = ‘INSERT INTO joke SET
joketext = :joketext,
jokedate = “today’s date”’;
$s =$pdo->prepare($sql);
$s-bindValue(‘:joketext’, $_POST[‘joketext’]);
$s->execute();

Why can’t you just do this instead

$pdo->prepare($sql);
bindValue(‘:joketext’, $_POST[‘joketext’]);
$pdo->execute();

Would you mind rephrasing and fixing your code? I’m having a bit of trouble following, especially since you have syntax errors, I’m not sure if they are intentional or not part of what you are asking.

added arrow to first bindValue

So bindValue in your second example is not correct syntax, nor is joketext or jokedate, they need $ in front. bindValue() needs run on an object.

joketext in your first exampel is never used, therefore not needed, same thing with jokedate.

no $ are needed in front. they’re not variables, they’re part of a MYSQL database.
Except for any typos, I pretty much copied it out of the book.

Ok sorry, I had trouble reading it because you didn’t use PHP highlighting. In any case:


$pdo->prepare($sql);
bindValue(':joketext', $_POST['joketext']);

is invalid syntax. bindValue() is not a global function, it is part of the PDOStatement class.

have a look at the return value here: http://www.php.net/manual/en/pdo.prepare.php

It returns an object (a class). That means you have to save the result so that you can use it. the reason you cant do $pdo->prepare and then immediately $pdo->bindValue is because bindValue() does not exist in PDO, it exists in PDOStatement. It’s just part of good object oriented design practices.

To give a metaphor:

$pdo is the tunnel that connects your database and your webserver.
$s is the car (query/statement) that you put suitcases (data) into, and then drive it through the tunnel.

It doesnt make any sense to say “add suitcase to tunnel”.
The tunnel doesnt know which car you’re putting the suitcase into. (It also doesnt care.)
There can be multiple cars waiting to go through the tunnel. (Typical tunnel builders; only build a one-lane tunnel.)

Thanks to K. Wolfel and StarLion. I kind of get it.

I probably need to read more on Object Oriented Programming to understand.

I have often wondered why some many examples use the bind method. I almost always just pass in the parameters as an array. You can do this without storing anything:


$pdo->prepare($sql)->execute(array('joketext' => $_POST['joketest']));