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:
'use strict';
get('/api/posts').then(response => {
if(response.items.length > 0) {
response.items.forEach(post => {
if(post.description.length > 0) {
// Possibile errore. null non ha una proprietà length
}
});
}
});
Quindi dobbiamo trattare questo valore in modo appropriato:
header('Content-Type: application/json');
$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;