mardi 6 janvier 2015

Build tree using SQLite and php - error with fetchArray

I use SQLite and PHP. I need build some tree like this



  • rootfolder - orange_folder1 - orange1

  • rootfolder - orange_folder2 - orange2

  • rootfolder - banana1 - freshbanana - banana1

  • rootfolder - banana1 - freshbanana - banana2

  • rootfolder - banana1 - notfreshbanana - banana1

  • rootfolder - banana2 - notfreshbanana - banana1

  • rootfolder - banana2 - notfreshbanana - banana2

  • etc.


But I get error with fetchArray


or


I get tree like this: - rootfolder - orange_folder1 - orange1 - rootfolder - orange_folder2 - orange2 - rootfolder - banana1 - freshbanana - banana1 - rootfolder - banana1 - freshbanana - banana2 - rootfolder - banana1 - notfreshbanana - banana1 - rootfolder - banana2 - notfreshbanana - banana1 - rootfolder - banana2 - notfreshbanana - banana2 - orange1 - orange2 - banana1 - banana2 - banana1 - banana1 - banana2


I created DB in SQLite



<?php
$db = new SQLite3("name.sqlite");

$db->exec('CREATE TABLE food (id INTEGER PRIMARY KEY, parent_folder_id INTEGER, name VARCHAR(10), type VARCHAR(10);');

$db->exec('INSERT INTO food (id, parent_folder_id, name, type) VALUES (1,null,"orange_folder1","folder");'); //in root
$db->exec('INSERT INTO food (id, parent_folder_id, name, type) VALUES (2,1,"orange1","file");'); // in orange folder
?>


Then I use this code:



<?php
function handler($directory){

global $db;
$stmt = $db->prepare('SELECT * FROM food'. ( $directory=='/' ? '' : ( ' WHERE parent_folder_id=' . $directory ) ) .';');
$result = $stmt->execute();

$data = array();

while ($row = $result->fetchArray()){
$temp_data = array(
"id" => $row['id'],
"name" => $row['name'],
"type" => $row['type']
);

if ($row['type']=='folder'){
/*$temp_arr = array();
$stmt = $db->prepare('SELECT * FROM food WHERE parent_id=' . $temp_data["id"].";");
$result1 = $stmt->execute();
while ($row1 = $result1->fetchArray()){
array_push($temp_arr, array(
"id"=> $row1['id'],
"name"=> $row1['name'],
"type"=> $row1['type']
)
);
}
$temp_data["data"] = $temp_arr;*/
$temp_data["data"] = dir($row["id"]);
}

$data[] = $temp_data;
}

$db->close();

return $data;
}

handler('/');
?>


Thanks.


Aucun commentaire:

Enregistrer un commentaire