Jump to content

[SOLVED] PHP null values


dg

Recommended Posts

If you var_dump() the result you'll probably see the data is still NULL, the string value of NULL is indeed blank. If you want to convert the NULL values to readable strings you can do something like this:

<?php
function convert_null($v) {
	return ($v === NULL) ? 'NULL' : $v;
}

while ($data = mysql_fetch_array($query)) {
	$data = array_map('convert_null', $data);
	print_r($data);
}
?>

$a = array("k"=> NULL,"n"=>'', "c"=>'test');

print_r($a);

 

gives me

Array

(

    [k] =>

    [n] =>

    [c] => test

)

 

but i want it to appear this way

 

Array

(

    [k] => NULL

    [n] =>

    [c] => test

)

 

is this possible using any built in php function which can be directly applied to the array?

ya .. that true if u want for printing purpose only

my prob is something different ....

 

i have two tables in mysql exactly same but in different databases

now wht i m doing is fetching the data from table1 and putting it into another table2

something like this :

while ($aSQL = mysql_fetch_array($sRst)) {

$sInsert = "Insert into table2 (a, b ,c) values ('".$aSQL['a']."', '".$aSQL['b']."', '".$aSQL['c']."')";

mysql_query($sInsert);

}

 

now imagine one of the field has a NULL value ..... in table2 it will be insert as blank..

 

and use of the function like array_map will apply to each element of the array....... and table with 20000 values ??

won't it affect the performance ....

 

i hope it's now clear .....

while ($aSQL = mysql_fetch_array($sRst)) {
	$aSQL['a'] = ($aSQL['a'] === NULL) ? 'NULL' : "'{$aSQL['a']}'";
	$aSQL['b'] = ($aSQL['b'] === NULL) ? 'NULL' : "'{$aSQL['b']}'";
	$aSQL['c'] = ($aSQL['c'] === NULL) ? 'NULL' : "'{$aSQL['c']}'";

	$sInsert = "Insert into table2 (a, b ,c) values ({$aSQL['a']}, {$aSQL['b']}, {$aSQL['c']})";
	mysql_query($sInsert);
}

The reason it is returning as an empty string, is because NULL is only a placeholder, and so you need to instead take the NULL value, and convert it to a string value. Like this:

 

<?php
while ($aSQL = mysql_fetch_array($sRst)){
     if(is_null($aSQL['myValue'])){
          $aSQL['myValue'] = 'NULL';
     }
     echo $aSQL['myValue'];  // this will either echo NULL or what was in the database
}
?>

hi ....

  found the solution....

  building the insert statement without the fields which has NULL values

  if ($aSQL['a'] === NULL) {

    do not include in the insert statement

  }

 

so by default since field is not present in insert statement it take NULL in the database ...

 

n works fine even if the filed has blank value ...since in the insert,  field is included...n goes as blank in the table  8)

 

thanx for the replies :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.