PHP: gestire il valore MySQL NULL in JSON

PHP: gestire il valore MySQL NULL in JSON

In PHP il valore MySQL NULL va gestito attentamente quando si usa JSON.

Supponiamo di avere un campo di una tabella che ha come valore MySQL predefinito NULL. Dato che questo valore è anche un valido valore JSON, la funzione json_encode() lo converte nel valore corrispondente.

Tuttavia, a livello client il valore null può generare errori in quelle proprietà degli oggetti in cui ci si aspetti un valore diverso come ad esempio una stringa:


$.get( "/ajax/posts", function( response ) {
    if( response.items.length > 0 ) {
        $.each( response.items, function( i, post ) {
             var description = post.description; // Possibile null
             if( description.length > 0 ) {
                 // Errore fatale! null non ha una proprietà length!
             }
        });
    }
});

Quindi dobbiamo trattare questo valore in modo appropriato:


header('Content-Type', 'application/json');

$db = require_once('db.php');
$posts = $db->get('posts');
$output = [];

foreach($posts as $post) {
    $output[] = [
        title => $post['title'],
        description => (!is_null($post['description'])) ? $post['description'] : ''
    ];
}

echo json_encode($output);
exit();

Torna su