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! While you're at it, check out some resources Treehouse students have shared here.

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

troy beckett
troy beckett
12,035 Points

fetching and binding in php

Just simply what is the need for fetch in php and what does it do. Same for binding. I just what to understand it's purpose not actual code. Thanks in advance for any help?

1 Answer

Codin - Codesmite
Codin - Codesmite
8,600 Points

Both are used with PDO (PHP Data Objects) for use with PDO compatible databases.

Bind allows you to obscure and sanitize values/parameters in paramatized/prepared statements using named or question mark placeholders to prevent injection.

Example using named placeholders:

<?php
$speed = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, speed
    FROM cars
    WHERE speed < :speed AND colour = :colour');
$sth->bindParam(':speed', $speed, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Example using question mark placeholders:

<?php
$speed = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, speed
    FROM cars
    WHERE speed < ? AND colour = ?');
$sth->bindParam(1, $speed, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Fetch is used for retrieving data from the database.

It is basically a better way to access your database then using mysql_ functions, especially as mysql is no longer being maintained/supported.