raqulka raqulka - 4 months ago 8
JSON Question

Only one array in json object

I have 5 tables for different files that user can upload. I would like to get all the files with corresponding data in one array so 5 files data in one array.

All the tables have same structure:

user_id, file_type, file_size, file_name, file_new_name, file_path, date_created


In PHP I am using this query
select * from degree_files, profile_pictures, cpr_files, backgroundcheck_files, video_files where degree_files.user_id = :user_id
which gives me all 5 file data if I run it in workbench, but json object is only one array.

How can I show all the data in one array or what would be the right solution, because right now I am querying each table separately?

I tried:

$backgroundCheck = $user_home->runQuery("select * from degree_files, profile_pictures, cpr_files, backgroundcheck_files, video_files where degree_files.user_id = :user_id");
$backgroundCheck->execute(array(":user_id"=>$user_id));
$nanny_backgroundCheck_file = $backgroundCheck->fetchAll(PDO::FETCH_ASSOC);


$file_name = array();
foreach ($nanny_backgroundCheck_file as $c){
$file_name[] = $c['file_name'];
}

$arr[] = array('file_name'=>$file_name);
echo json_encode($arr, JSON_UNESCAPED_UNICODE);


And AJAX call:

$.getJSON("PHP/nannyInfo.php", function(data) {
//SELECT2 DATA
$.each(data.nanny_backgroundcheck_file, function(index, data) {
console.log(data);

});

});


What I see in console.

enter image description here

Answer

The query first. You're trying to get a single column from multiple tables, right? If so, I'd suggest this syntax:

$sql = "
    select file_name from degree_files where user_id = :user_id
    UNION select file_name from profile_pictures where user_id = :user_id
    UNION select file_name from cpr_files where user_id = :user_id
    UNION select file_name from backgroundcheck_files where user_id = :user_id
    UNION select file_name from video_files where user_id = :user_id";

Then, the actual SQL execution is mostly OK but I'd simplify it to:

$backgroundCheck = $db->prepare($sql);
$stmt->execute(array(":user_id"=>1)); // 
$fileNames = $stmt->fetchAll(PDO::FETCH_COLUMN, 'file_name');

echo json_encode($fileNames, JSON_UNESCAPED_UNICODE);