Using rowCount() isn't unsafe, but just improper.
The #1 rule when working with databases is
Always select the exact data you need.
with as less post-processing as possible.
So if you need to check whatever data for existence, then ask your database to check and then fetch the result.
However, you have to keep in mind that there are 2 possible scenarios:
In case you indeed need to check wherever something exists in a database, but don't need the data, then (assuming username has an unique index on it):
$sql = "SELECT 1 FROM users WHERE username = ?";
$result = $db->prepare($sql);
$result->execute(array('administrator'));
echo $result->fetchColumn() ? 'true' : 'false';
But often you need the data itself if it happens to be found. In this case you just select that data:
$sql = "SELECT * FROM users WHERE username = ?";
$result = $db->prepare($sql);
$result->execute(array('administrator'));
$user = $result->fetch();
echo $user ? 'true' : 'false';
I am stressing on it because the wording of the other answer suggests that you have to run 2 queries: one to check the existence and one to get the data, which is a nonsense.
As of the rowCount()
method - you need it too seldom to talk about.