skip to Main Content

Can anyone please help me get the count of the filled MySQL columns?

For example:
My Table Structure:

ID FName LName
1 ABC NULL
2 XYZ

In the above table, I have two Rows, and both rows contain one Null and One Empty Value, I just need to get the Count of each row that doesn’t have NULL OR EMPTY Value for a specific ID.


Expected Result:

WHERE ID=1, the result would be:
Count = 2 (ID, FName)

WHERE ID=2, the result would be:
Count = 2 (ID, LName)


**I want to use this in WordPress

2

Answers


  1. Chosen as BEST ANSWER

    So, after searching for an hour or two.

    I'm using this as my solution but I'm not sure if it's good regrading the optimization. Here is what I'm using:

    function ranking_mechanism( $currentUserID ){
    global $wpdb;
    $rank = 0;
    
    $results = $wpdb->get_row(
        $wpdb->prepare('SELECT * FROM TABLE WHERE ID=%d', $currentUserID)
    ); 
    
    $finalArr = (array) $results; // Convert $results as Array(to perform iteration), it(WordPress DB Query) typically return Object by Default 
    foreach ( $finalArr as $key => $Table ) {
        if( $finalArr[$key] == '' || $finalArr[$key] == 'NULL' ){
            // Nothing to do 
        }else{
            $rank = $rank+1; // Increase Rank If Found Value
        }
        return $rank;
    }
    

  2. SELECT ID,   (ID IS NOT NULL) /* assuming that ID is numeric and cannot be empty string */
               + (FName <> '' AND FName IS NOT NULL) 
               + (LName <> '' AND LName IS NOT NULL) AS `Count`
    FROM source_table
    -- WHERE ID = ???
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search