Paul Dessert
Paul Dessert

Reputation: 6389

Simple MySQL SELECT with PDO

How do I filter by columns with PDO? I have the following:

$sth = $dbh->query('SELECT * from blog ORDER BY date DESC LIMIT 4');  

This obviously returns the last 4 results. I want to add one more step and filter it by a specific column named category

So, something like:

$sth = $dbh->query('SELECT * from blog WHERE category=NAME-HERE ORDER BY date DESC LIMIT 4'); 

Thanks!

Upvotes: 1

Views: 1744

Answers (1)

Justin ᚅᚔᚈᚄᚒᚔ
Justin ᚅᚔᚈᚄᚒᚔ

Reputation: 15369

I would suggest using prepared statements with named parameters:

$stmt = $dbh->prepare("SELECT * FROM blog WHERE category=:category ORDER BY date DESC LIMIT 4");
$stmt->bindParam(':category', $category);
$stmt->execute();

PDO will automatically wrap quotes around the category parameter if it is a string.

If the value of $category isn't coming from an untrusted source, you can modify your code as follows:

$sth = $dbh->query("SELECT * from blog WHERE category='$category' ORDER BY date DESC LIMIT 4");
/** OR **/
$sth = $dbh->query('SELECT * from blog WHERE category="'.$category.'" ORDER BY date DESC LIMIT 4');

Note that in the above case, you do need quotes around the $category variable since you're building the query string yourself.

Upvotes: 4

Related Questions