PDA

View Full Version : Important note to MYSQL , PHP and datatypes



Stju
17 Mar 2010, 2:27 AM
Maybe someone of You are not aware that MySql returns all data as strings..
JavaScript expects to see boolean values as boolean and numbers as numbers, otherwise this can led to some unpredictable problems.
This is simple solution to solve typecasting problem :">
To illustrate (without use of fix_cast) json_encode result:


[{"number":"5","boolean_value":"true"}]
Using fix_cast:


[{"number":5,"boolean_value":true}]


Here comes the medicine:


function fix_cast(&$value, $key){
if($value=='false' || $value=='true'){$value = $value=='true' ? true : false;} //fix boolean values!
if(is_numeric($value))$value= (int)$value; //fix numeric values!!
}
array_walk_recursive($store_data, 'fix_cast');
Hopefully this will save some headache..
Use this straight after MySql request applying to resulting data-set.

Stju

der_ele
19 Apr 2010, 2:30 PM
Nice snippet! But not every numeric value must be an integer..
Especially a decimal: If the numeric string is 0.999 the result would be 0 because the typecast cuts off the rest.



$store_data = array("number"=>"5","decimal"=>"0.9","string"=>"asd","boolean_value"=>"true");
function fix_cast(&$value, $key){
if($value == 'false' || $value == 'true') $value = ($value == 'true'); //fix boolean
elseif((string)(float)$value === (string)$value) $value = (float)$value; //fix float
elseif(is_numeric($value)) $value= (int)$value; //fix numeric
}
array_walk_recursive($store_data, 'fix_cast');

echo json_encode($store_data);


Output without fix:


{"number":5,"decimal":0,"string":"asd","boolean_value":true}


Output with fix:


{"number":5,"decimal":0.9,"string":"asd","boolean_value":true}


Maybe there are more cases than mine and yours..
greetz ele

der_ele
19 Apr 2010, 11:35 PM
one night sleeping...



<?php

$store_data = array("number"=>"5","decimal"=>"0.9","string"=>"asd","boolean_value"=>"true", "nan"=>NAN, "exp"=>"1.4E+6");
function fix_cast(&$value, $key){
if($value == 'false' || $value == 'true') $value = ($value == 'true'); //fix boolean
elseif(is_nan((double)$value)) $value = 0; // fix NAN
elseif(is_numeric('0'.$value))$value = ((float)$value != (int)$value)?(float)$value:(int)$value; //fix numeric
}
array_walk_recursive($store_data, 'fix_cast');

echo json_encode($store_data);

?>
Has anyone an idea how to include it into the extDirect so that every call before a return isnt needed?

greetz ele