php - using for loop on mysql table

905

I have 2 tables on my db: cat (id, catname) link (id, name, url, cat)

I wanted to loop through the tablelink and output data bycat, here the actual code but id doesn't work anyway :)

    for ($i = 1; ; $i++)
    {
        $list = $mysqli->query('SELECT * FROM links WHERE category='$i'');
        while($row = $list->fetch_assoc()) {
            print $row["category"];
            print $row["name"].' ';
            print $row["url"];
            print '<br>';
        }
    }

    $list->free();

Is there a way we can get theid from tablecat and use that to loop through the data in tablelink? Thanks

801

Answer

Solution:

No need for so many requests inside the loop. There are JOIN statements in SQL for such cases:

$result = $mysqli->query('SELECT category.name AS cat_name, 
                               links.name,
                               links.url 
                          FROM category 
                          INNER JOIN links ON links.cat=category.id');

while($row = $result->fetch_assoc()) {
    print $row["cat_name"];
    print $row["name"].' ';
    print $row["url"];
    print '<br>';
}

$result->close();

People are also looking for solutions to the problem: php - Strange, annoying and very random session timeout

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.