问题
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';
回答1:
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';
回答2:
SELECT 1 FROM users WHERE username = 'administrator' LIMIT 1
回答3:
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.
来源:https://stackoverflow.com/questions/37958770/what-is-the-best-way-to-check-if-something-exists-with-pdo