What is the best way to check if something exists with AOP

advertisements

This question already has an answer here:

  • Row count with PDO 20 answers

Some one told me rowCount not safe so I like to ask it here, I have 2 examples and like to know what is the safest and nice way to check if something exists?

$sql = "SELECT count(*) FROM users WHERE username = 'administrator'";
$result = $db->prepare($sql);
$result->execute();
echo $result->fetchColumn() ? 'true' : 'false';

or

$sql = "SELECT username FROM users WHERE username = ?";
$result = $db->prepare($sql);
$result->execute(array('administrator'));
echo $result->rowCount() ? 'true' : 'false';


The best way to check it with prepare and fetchColumn

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.

$sql = "SELECT COUNT(*) FROM users WHERE username = ?";// use `COUNT(*)`
$result = $db->prepare($sql);
$result->execute(array('administrator'));
echo $result->fetchColumn() ? 'true' : 'false';