简体   繁体   中英

PHP Oracle OCI8 query to keep/handle null columns in array

I have the below sql query.. in which I'm mapping the contents to a kendo front-end table..

$sql = "SELECT big_id, fac_ident, lg_name, basic_tp, catc_vd, address, assoc_city, latitude, longitude, assoc_cnty, assoc_st, time_zone, faa_reg, ato_sa, ato_td, fema_reg, ops_hrs, prim_ph, atc_level, tower_type, manager, sat_phone_num, td_mgr, to_dist, tod_mgr, stof_fac, ops_status, crt_rl FROM myCoolApp.big_id";

The problem is.. columns that are not finding any associated value in the DB, is not returning any value back, and alas just completely omitted from the response array.. ie in ops_hrs above no value is found, so it's completely omitted from my array - I need it to still exist, just be blank.

I would like the response to still display the column in the array even when it's value is empty ; ideally just adding a blank space " " or 'N/A' even. As I do not want the null column to be dropped in my array and front-end.

The rest of my PHP/sql...

        $stid = oci_parse($this->db, $sql);
        oci_execute($stid); 
            
        $myData = array();

        while ($list = oci_fetch_array($stid, OCI_ASSOC)) {
            array_push($myData, $list);
        }
    
        header('Content-Type: application/json');
        echo "{\"data\":" .json_encode($myData). "}";

What am I missing here? I need to handle it programmatically with PHP/sql.

Use OCI_RETURN_NULLS :

while ($list = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    array_push($myData, $list);
}

See the PHP OCI8 oci_fetch_array documentation .

As of SQL (and Oracle), you could use the NVL function which returns column value if it exists, or its "substitute" if it does not.

For example, in this query comm column's value is NULL :

SQL> select ename, comm from emp where empno = 7369;

ENAME            COMM
---------- ----------
SMITH

You'd then

SQL> select nvl(ename, 'N/A') as ename,
  2         nvl(comm , 0    ) as comm
  3  from emp
  4  where empno = 7369;

ENAME            COMM
---------- ----------
SMITH               0

SQL>

Pay attention to column's datatype. If it is a string, NVL should return a string as well (such as 'N/A' ); if it is a number, let it return a number (such as 0 ), etc.

There's no "universal" way to do it, so you'll have to apply NVL to all columns you're selecting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM