Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 9 of 9
  1. #1
    Senior Coder doubledee's Avatar
    Join Date
    Mar 2011
    Location
    Arizona
    Posts
    1,097
    Thanks
    26
    Thanked 0 Times in 0 Posts

    Best way to check if variable is empty

    I have a variable called $messagesToUpdate that holds any and all Messages that have been checked so that an action can be taken on them.

    This variable is populated using the implode function if values were submitted in one of two $_POST arrays.

    An example of what this variable would hold if the User selected some Messages to take actions on, would be this...

    Code:
    $messagesToUpdate = 52, 51, 49, 39, 38, 10, 8, 6, 5, 2, 1

    So on to my question...

    If this variable has at least one value, then I want to run an UPDATE query, but if it is blank then the query should not be run.


    What is the best way to check if this variable is blank?


    I was starting to use this, but am not sure if it covers all cases...
    Code:
    	if (!empty($messagesToUpdate)){
    		// Update Selected Messages.
    				
    	}else{
    		// Do nothing.
    				
    	}
    I'm unsure what is the best way to check for Blank, Null, Empty, Zero-Length String, etc.

    Suggestions??

    Thanks,


    Debbie

  • #2
    Senior Coder doubledee's Avatar
    Join Date
    Mar 2011
    Location
    Arizona
    Posts
    1,097
    Thanks
    26
    Thanked 0 Times in 0 Posts
    Maybe this is better...
    Code:
    	if (isset($messagesToUpdate) && $messageToUpdate){

    Debbie

  • #3
    Regular Coder
    Join Date
    Jul 2012
    Location
    London
    Posts
    473
    Thanks
    4
    Thanked 86 Times in 86 Posts
    PHP Code:
    // Function for basic field validation (present and neither empty nor only white space
    function IsNullOrEmptyString($messagesToUpdate){
        return (!isset(
    $messagesToUpdate) || trim($messagesToUpdate)==='');

    Original: http://stackoverflow.com/a/381275

  • #4
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    For this you need to describe empty in your definition of it. From what I gather, you do not consider a space delimited string to be empty (and nor should you as it is not empty), so you would use the empty() function for that. Empty is true so long as the item it is given equates to false, so that will be false, 0, 0.0, "", "0", array(), null and uninstantiated object properties.
    Assuming that 0 is never valid and you cannot possibly end up with spaces than empty is sufficient. Or you can never convert it to a string and retain it as an array and use the empty or count on the array instead. Arrays are far more useful than a string anyways.

  • #5
    Senior Coder doubledee's Avatar
    Join Date
    Mar 2011
    Location
    Arizona
    Posts
    1,097
    Thanks
    26
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Fou-Lu View Post
    For this you need to describe empty in your definition of it. From what I gather, you do not consider a space delimited string to be empty (and nor should you as it is not empty), so you would use the empty() function for that. Empty is true so long as the item it is given equates to false, so that will be false, 0, 0.0, "", "0", array(), null and uninstantiated object properties.
    Assuming that 0 is never valid and you cannot possibly end up with spaces than empty is sufficient. Or you can never convert it to a string and retain it as an array and use the empty or count on the array instead. Arrays are far more useful than a string anyways.
    I'm not following you.

    In my HTML section, I have this code, which populates the selectedMsgArray with an entry for each Private Message that is checked...

    PHP Code:
        // Loop through Messages.
        
    while (mysqli_stmt_fetch($stmt6)){
            echo 
    "<tr" . (is_null($readOn) ? " class='pmUnread'" "") . ">
                    <td class='colSelect'>
                        <input id='"
                        
    str2htmlentities($pmID)
                        . 
    "' name=selectedMsgArray["
                        
    str2htmlentities($pmID)
                        . 
    "] type='checkbox' value=1 />
                    </td> 

    Then at the top of my script - in the section handles the submitted Form - I have this snippet...

    PHP Code:
        // **************************
        // Mark Incoming as Unread.    *
        // **************************
        
    if (!empty($_POST['selectAll']) && $_POST['selectAll'] == 1){
            
    // All Messages Selected.
            
    echo "All Messages Selected<br />";

            
    $messagesToUpdate implode(', 'array_keys($_POST['msgArray']));

        }elseif (!empty(
    $_POST['selectedMsgArray']) && $_POST['selectedMsgArray']){
            
    // Some Messages Selected.
            
    echo "Some Messages Selected<br />";

            
    $messagesToUpdate implode(', 'array_keys($_POST['selectedMsgArray']));

        }else{
            
    // No Messages Selected.
            
    echo "No Messages Selected<br />";

            
    $messagesToUpdate '';

        }
    //End of MARK INCOMING AS UNREAD

        
    echo '$messagesToUpdate = ' $messagesToUpdate;


        if (isset(
    $messagesToUpdate) && $messagesToUpdate){
    //            if (!empty($messagesToUpdate)){
            // Update Selected Messages.

            // Build query.
            
    $q1 "UPDATE private_msg_recipient...

        }else{
            // Do nothing.

        } 
    If the User never checked any PM's, then $messagesToUpdate = '' and I do NOT want my UPDATE query to run.

    Above you can see the code I commented out, and what I have now, which seems to make sense.

    Follow me?


    Debbie

  • #6
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    I'm not saying it won't work, I'm saying you're doing more work than you need.
    There is no reason to convert to a string prior to checking the count. I'm not sure why you are passing a msgArray on top of a selectedMsgArray; if you are updating all do you really need the msgArray? Maybe its for a pagination option so you only update a page at a time (which is fine)?
    In any case, keep it as an array until you need to actually use it.
    PHP Code:
    $aToDelete = array();
    $sMsg "No Messages Selected";
    if (isset(
    $_POST['selectAll'])) // assuming a checkbox
    {
        
    $aToDelete $_POST['msgArray'];
        
    $sMsg 'All Messages Selected';
    }
    else if (
    count($_POST['selectedMsgArray']) > 0// or use empty
    {
        
    $aToDelete $_POST['selectedMsgArray'];
        
    $sMsg 'Some Messages Selected';
    }

    if (!empty(
    $aToDelete))
    {
        
    // do the query.
    }
    print 
    $sMsg

  • #7
    Senior Coder doubledee's Avatar
    Join Date
    Mar 2011
    Location
    Arizona
    Posts
    1,097
    Thanks
    26
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Fou-Lu View Post
    I'm not saying it won't work, I'm saying you're doing more work than you need.
    There is no reason to convert to a string prior to checking the count.
    Because you apparently can't use the IN keyword with Prepared Statements with any amount of ease, this no longer applies, because I am going back to my Looping approach.

    However...

    I'm not sure why you are passing a msgArray on top of a selectedMsgArray; if you are updating all do you really need the msgArray? Maybe its for a pagination option so you only update a page at a time (which is fine)?
    I have issues with JavaScript, so I am doing everything server-side on this page.

    I want it so if the User checks the Top Check-Box, then whatever "action" they choose will apply to all Messages. In order to make that happen, I need to do this...
    PHP Code:
        echo "<input name='msgArray[" str2htmlentities($pmID) . "]' type='hidden' value=1 />"

    That works great if you want to apply some "action" to everything, but I also need the ability for a User to cherry-pick the 1st, 3rd, 5th, and 6th Messages and have the "action" apply to just those selected ones. For that I chose to store things in a separate array. probably not the most efficient, but I have been screwing with this script for the last 3 weeks, and I need to get it done, so that is what I went with.

    Feel free to offer a better approach - without JS - if you want!

    Thanks,


    Debbie

  • #8
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    There's hardly anything wrong with looping and a prepared statement. At least this way you only send the data chunk between the dbms and the PHP instead of the whole statements, so that's okay. It is admittedly more complex to use an IN with a prepared statement if you don't know the exact number of options:
    PHP Code:
    $a = array(11719);
    $sIn implode(', 'array_fill(0count($a), '?'));
    $sQry "SELECT * FROM mytableofnames WHERE id IN ($sIn)";
    if (
    $stmt $db->prepare($sQry))
    {
        
    $aParams = array(str_repeat('i'count($a)));
        foreach (
    $a AS &$itm)
        {
            
    $aParams[] = &$itm;
        }

        
    call_user_func_array(array($stmt'bind_param'), $aParams);
        
    $stmt->execute();
        
    $stmt->bind_result($id$name);

        while (
    $stmt->fetch())
        {
            
    printf('%d: %s' PHP_EOL$id$name);
        }
        
    $stmt->close();

    Personally I'd say using a loop and binding single params is easier. Means more going out to the dbms, but even so you shouldn't see any significant change from using an IN clause.

    Still not seeing the need for msgArray. If you are referring to everything, than what reason would you need to send this information back to the server for? The server came up with the data in the first place, so would it not be easier to update on the same criteria that the select was given if it detects that the selectAll checkbox has been selected?

    Always assume that there is no JS available. JS should be massaged to talk to PHP, not the other way around.

    Edit:
    BTW, using PDO would actually be easier for an IN clause. The PDO library binds on a call by call basis while the mysqli only allows a single call to bind.
    Last edited by Fou-Lu; 01-06-2013 at 04:10 PM.

  • #9
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    There's hardly anything wrong with looping and a prepared statement.
    @Fou-Lu I had forgotten about the prepared statements aspect! Kinda their whole purpose really .

    Still not seeing the need for msgArray.
    This may relate to a previous suggestion I made. If the messages were paginated, then re-executing the same SQL-criteria may not produce the same messages, as a message may have been deleted or created on a previous page (in another tab). I see that you picked up on this possibility in a previous post.
    Last edited by AndrewGSW; 01-06-2013 at 04:37 PM.
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •