Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Integrating PHP with Databases Using Relational Tables Preparing SQL Statements

Hashim Amun
Hashim Amun
3,434 Points

Why PDO STR string in Preparing SQL Statements Bind Param?

Hi guys, been doing a little extra research and I notice that in php.net the PDO filter STR for bind param:

$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);

includes a number after the string filter:

$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);

I guess this refers to the string length of the named parameter and the variable it's binding to (':colour', $colour,). But this is where it gets a little fuzzy.

Can someone tell me:

1) If the number reflects the string length of the named parameter & variable.

2) Why they are including the string length (what's the purpose? what does it do?).

3) What happens if the variable you are passing is a string in the form of an integer (e.x. "007" as in agent 007).

Thanks, and I love the simplicity, illustrations, and upbeat environment of the lessons, by the way.

2 Answers

Chris Shaw
Chris Shaw
26,676 Points

Hi Hashim Amun,

First and foremost, I recommend you have a read of Posting Code to the Forum which has a lot of examples for code formatting.

The length parameter can be a little confusing if you have never used stored procedures before, in normal bindings we can forget about this altogether as a length is only required when using output parameters which are unique to CALL procedures. This functionality is beyond the scope of what Treehouse covers but you can visit the SitePoint article I've linked below which covers the basics of the topic.

I have also linked to some examples from IBM and PHP.net which are pretty basic but require a level of understanding before they will make sense.

In the case of this course and others that make use of PDO bindings, you can safely avoid the length parameter.

Happy coding!

Hashim Amun
Hashim Amun
3,434 Points

Hey Chris, thanks so much for getting back and helping explain this, and the additional resources you've provided.