I want some advice on structuring some (basic) php code.
I need to display data from a table in different places. The rows that need to be displayed in each section can be identified by a flag.
I’m not sure if the best way to do this is to go to the database once and seperate the data into 2 variables as I loop through it or if I should go to the database twice, using sql to call only the data I need each time.
For those who want to see it in code:
Method A:
// Create and execute a MySQL query
function tasks_not_done(){
// Open a PDO dtabase connection
$link = new PDO(DB_INFO, DB_USER, DB_PASS);
$sql = " SELECT title, created_date
FROM todos
WHERE list_id = ? AND checked = '0'
ORDER BY created_date DESC";
$stmt = $link->prepare($sql);
$stmt->execute(array($_REQUEST['list_id']));
// loop throught all the rows
while($row = $stmt->fetch()) {
$date = strtotime($row['created_date']);
$date = date('d/m/y' , $date);
echo '<div class="task">' . "\n";
echo '<span class="taskcdtate">' .$date . '</span>'. '<span class="tasktitle"> ' . $row['title'] . ' </span>' . "\n";
echo '</div>';
}
$stmt->closeCursor();
}
Method B
function tasks_all(){
// Open a PDO dtabase connection
$link = new PDO(DB_INFO, DB_USER, DB_PASS);
$sql = " SELECT title, created_date, checked
FROM todos
WHERE list_id = ?
ORDER BY created_date DESC";
$stmt = $link->prepare($sql);
$stmt->execute(array($_REQUEST['list_id']));
// loop throught all the rows
$tasks['not_done'] = "";
$tasks['done'] = "";
while($row = $stmt->fetch("FETCH_ASSOC")) {
$date = strtotime($row['created_date']);
$date = date('d/m/y' , $date);
if($row['checked'] =='0'){
$tasks['not_done'] .= '<div class="task">' . "\n";
$tasks['not_done'] .='<span class="taskcdtate">' .$date . '</span>'. '<span class="tasktitle"> ' . $row['title'] . ' </span>' . "\n";
$tasks['not_done'] .='</div>';
} elseif ($row['checked'] =='1') {
$tasks['done'] .= '<div class="task">' . "\n" .
$tasks['done'] .='<span class="taskcdtate">' .$date . '</span>'. '<span class="tasktitle"> ' . $row['title'] . ' </span>' . "\n";
$tasks['done'] .='</div>';
}
}
$stmt->closeCursor();
return $tasks;
}
thanks
There is no right answer to this kind of question, but I can give you some pointers.
My general rule is: get the data you need when you need it. But there are a lot of things that could affect this.