我遇到以下查询的问题,该查询应该计算数据库中的Null和Not Empty记录。我需要使用预准备语句来执行。我有以下代码,但我无法得到正确的输出。任何帮助将不胜感激!
$query = "SELECT UserName, COUNT(NULLIF(TRIM(UserName), ''))
FROM Employee";
$stmt = $db->prepare($query7);
$stmt->execute();
$stmt->store_result();
$numrows = $stmt->num_rows;
$stmt->bind_result($Count);
for ($i=0; $i <$numrows; $i++) {
$stmt->fetch();
echo "Count: $Count";
};
答案 0 :(得分:1)
To count non-null and non-empty records, you can do:
SELECT COUNT(*)
FROM Employee
WHERE UserName IS NOT NULL AND UserName != ''
You don't need to use TRIM(UserName)
, because trailing spaces are ignored when comparing strings.
The full PHP code should be like this:
$query = "SELECT COUNT(*)
FROM Employee
WHERE UserName IS NOT NULL AND UserName != ''";
$stmt = $db->prepare($query);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($Count);
$stmt->fetch();
echo "Count: $Count";