Search code examples
phpmysqlselect

Presetting a result for a particular column in mysql?


My app's javascript is set up to display certain columns of mysql data, but if a particular column (col3) has no data in it, the js won't display col3's data, just the rest from the mysql SELECT statement ie if col3="", don't display col3.

In some circumstances, I'd like the js to not display it regardless if there is data in it, but I'd prefer to code the logic in php.

Currently, if I just leave col3 out of the select statement, js displays it as "undefined".

I'm wondering if there is a way in a mysql SELECT statement to make col3 equal an empty string regardless if it has data in it?

Or must I set each of the col3 results to "" in...

while ( $row=$result->fetch_assoc() ) { $row['col3']=""; $resultArray[]=$row; }

Thank you.


Solution

  • Your best bet is probably ISNULL or related functions.


    On the PHP side, you can use array_merge:

    Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

    For instance:

    $defaults = array( 'col3' => '' );
    $row = array_merge( $defaults, $row );
    

    If you know your values are going to be NULL (and not nonexistant), then use the following function (untested):

    function array_merge_isset() {
      $args = func_get_args();
      $result = array();
      foreach( $args as $arr ) {
        if( !is_array( $arr ) ) {
          continue;
        }
    
        foreach( $arr as $k=>$v ) {
          if( isset( $v ) ) {
            $result[ $k ] = $v;
          }
        }
      }
      return $result;
    }