All answers suggesting to use rowCount() are wrong, rowCount() returns a non zero value only in operations that Affect rows, not selected rows, or at least as sated in PHP manual: PDO::Statement it's not guarantied.
PDOStatement::rowCount() returns the number of rows
affected by
the last DELETE, INSERT, or UPDATE statement executed by the corresponding
PDOStatement object.
If the last SQL statement executed by the associated PDOStatement was a SELECT
statement, some databases may return the number of rows returned by that statement.
However, this behaviour is not guaranteed for all databases and should not be
relied on for portable applications.
More Text From The Manual
Example #2 Counting rows returned by a SELECT statement
For most databases, PDOStatement::rowCount() does not return the
number of rows affected by a SELECT statement. Instead, use
PDO::query() to issue a SELECT COUNT(*) statement with the same
predicates as your intended SELECT statement, then use
PDOStatement::fetchColumn() to retrieve the number of rows that
will be returned. Your application can then perform the correct
action.
At least I know that I had tons of problems with it.
One other way is to use:
$rows = stmt->fetchAll(PDO::FETCH_ASSOC);
if (count($rows))
{
//Do something here
}
else
{
//Do something else here.
}
The above chunk of code is good if you expect small data sets returned. If we're talking about huge data sets, then you're better of executing 2 queries, one with a COUNT in it with the same conditions as your select statement and then the SELECT statement like this:
$sql = "SELECT COUNT(*) FROM $tbl_name WHERE myData ='$MyData";
$count = $db->query($sql)->fetch();
if ($count[0] > 0)
{
$myQuery = "SELECT * FROM $tbl_name WHERE myData ='$MyData'";
//.... Continue your code here since now you know for sure that your
//query will return rows....
//.....
}
else
{
//handle the case that no data were returned.
}
The code chunks above are just for demonstration, so you can understand what and how to do.
I can't guarantee that this is the best way to do it, it's just the way I do it. Cheers.
Also a better way to do your thing is to use Prepared Statements as someone or some suggested. That has nothing to do with the way you're gonna deal with your problem here, it's just a safer practice in general since prepared statements prevent SQL Injection if not completely then to a really good degree (not sure about it).