1

I am having a problem with the following query that should count Null and Not Empty records in database. I need to use a prepared statement to execute. I have the following code but I cant get the correct output. Any help would be greatly appreciated!

$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";
    };
12
  • Your query counts non-Null and non-empty records. Commented Apr 1, 2016 at 1:21
  • Why are you also selecting UserName? That will just pick an arbitrary username from the table. Why do you use a loop to print the results, since there's just one row with the total for the entire table. Did you mean to group the data in some way? Commented Apr 1, 2016 at 1:23
  • Please show some sample data and the expected output. Commented Apr 1, 2016 at 1:23
  • I am actually trying to count the values that are NOT NULL and NOT EMPTY. I just need a single 'total' number to display. I guess I don't really need a loop to print the results then. I don't need to group the data, I just need to count how many records in the table have the defined value 'UserName'. Commented Apr 1, 2016 at 1:33
  • I also just tried this but still no output $result=mysql_query("SELECT SUM(UserName IS NOT NULL OR TRIM(UserName) != '') FROM Employee"); $Count=mysql_fetch_assoc($result); echo "Total: $Count"; Commented Apr 1, 2016 at 1:40

1 Answer 1

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";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.