views:

101

answers:

2

How can I convert the php function in the code below to a non-function.

<?php
require_once ('./mysqli_connect.php'); // Connect to the db.

function make_list ($parent)
{
    global $tasks;
    echo '<ol>';
    foreach ($parent as $task_id => $todo)
    {
        echo "<li>$todo";
        if (isset($tasks[$task_id]))
        { 
            make_list($tasks[$task_id]);
        }
        echo '</li>';
    }

    // Close the ordered list:
    echo '</ol>';
}

$mysqli = new mysqli("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT task_id, parent_id, task FROM tasks WHERE date_completed='0000-00-00 00:00:00' ORDER BY parent_id, date_added ASC");

if (!$dbc)
{
    // There was an error...do something about it here...
    print mysqli_error();
} 
$tasks = array();

while (list($task_id, $parent_id, $task) = mysqli_fetch_array($dbc, MYSQLI_NUM))
{
    // Add to the array:
    $tasks[$parent_id][$task_id] =  $task;
}

make_list($tasks[0]);

mysqli_close(); // close the connection

// Include the html footer
include('./includes/footer.html');
?>

Would it be better to leave my code like this even though the rest of my code that I have not posted is in non function form.

+8  A: 

First: You can't convert a recursive function to spaghetti code in an easy way.
Second: There is no point to do that. Separate your logic, the actions into functions, as well the logic and the presentation of the data. Don't spam your code with html tags. Use some kind of template mechanism.

erenon
+1  A: 

in addition to erenon's answer (which i fully support, he already made the points why your question is leading into the wrong direction):

use (or create) some database abstraction class that hides connecting, query execution etc. makes it much easier to change databases or adapt to interface changes later, and you have a central place for error handling.

and don't talk to the database as superuser ..

pfote