Eric
Eric

Reputation: 15

Run PHP loop with variables

Searched for the solution- found nothing. Maybe I used the wrong terms.

I try to split the server-side operations and the html structure. So I made two different files, first the index.php and then operation.php.

Inside of the operation.php I made a mysqli query and fetched the content of an mysql table into different variables:

$query = "SELECT * FROM work";
    if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_assoc()) {
        $title = $row["title"]; 
        $desc = $row["desc"];
        $id = $row["id"];
        $date = $row["date"];
        $time = $row["time"];
        $kat = $row["kat"];
        $user = $row["user"];
    }
    $result->free();
    }
$mysqli->close();
?>

Now I tried to use this in the index.php by including the operation.php and using it like

<div><?php echo $title ?></div>

Everything works, but I want to loop this div and get one <div> for every 'title' row in the database.

How is this possible?

Thanks in advance.

Upvotes: 0

Views: 103

Answers (1)

Dennis
Dennis

Reputation: 394

Well, you could declare an array at the top

$rows = array();
...
while ($row = $result->fetch_assoc()) {
    $rows[] = $row;
}
....

foreach($rows as $row) {
    echo '<div>' . $row['title'] . '</div>';
}

That could be a solution.

On the other hand, if you want to separate the logic and the view, you could take a look at MVC design patterns, or use a templating engine (like Twig for example)

What a templating engine allows you to do is something like this (not tested ;-)

$variables = array();
while ($row = $result->fetch_assoc()) {
    $variables['rows'][] = $row;
}
$twig->render('index.html.twig', $variables);

And in the separate index.html.twig you can use the templating language

...
<body>
{% for row in rows %}
    <div>{{ row.title }}</div>
{% endfor %}
</body>

I hope this helps :)

Upvotes: 1

Related Questions