0

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

2
  • So when you console.log(data) - what do you see? Commented Jul 19, 2016 at 6:30
  • @u_mulder check the edit Commented Jul 19, 2016 at 6:32

1 Answer 1

2

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);
$backgroundCheck->execute(array(":user_id"=>1)); // 
$fileNames = $backgroundCheck->fetchAll(PDO::FETCH_COLUMN, 'file_name');

echo json_encode($fileNames, JSON_UNESCAPED_UNICODE);
Sign up to request clarification or add additional context in comments.

3 Comments

I like the prepare, also protects agains sql injections.
@jirka Thank you man! but what if I want to get all the data from these 5 tables?
@jirka cant thank you enough. you are the legend. Couldnt think of the UNION.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.