Page 1 of 1

[simple] menu loading from mysql db

Posted: Tue Jun 21, 2011 2:37 am
by runeqm
i know this is very easy and probably not the most secure someone might find some use
<?php
function vertical_menu() {
    mysql_connect('localhost','root','');
    mysql_select_db("menu");
    $result = mysql_query("SELECT name,link FROM menu");
    while ($row =mysql_fetch_array($result)){
        $name=$row['name'];
        $url=$row['link'];
    echo "<a href ='$url'>$name</a> <br /> ";
    }
    
}
function hori_menu() {
    mysql_connect('localhost','root','');
    mysql_select_db("menu");
    $result = mysql_query("SELECT name,link FROM menu");
    while ($row =mysql_fetch_array($result)){
        $name=$row['name'];
        $url =$row['link'];
        echo "<a href ='$url'>$name</a> || ";
    }
    
}


?>
when i get the cast off my hand ill work on the basic functions of a game and release code just because it will help me learn more

Re: [simple] menu loading from mysql db

Posted: Tue Jun 21, 2011 7:08 am
by Tino
First of all, it would be better to just connect to MySQL just once outside the functions rather than twice within the functions. Also, inside those while loops you do some pointless variable assignments. Why not just use $row['link'] when you print the link?

And something unrelated to PHP, but if you're creating a menu/navigation, you'll generally want your links to be within an unordered list, since it's a list of links. So you could do something like:
echo '<ul>';

while ( $row = mysql_fetch_assoc($result) ) {
    echo "<li><a href=\"{$row['link']}\">{$row['name']}</a></li>";
}

echo '</ul>'
Then you could simply use some CSS to get rid of the annoying bullets.
ul { list-style-type: none; }
And in the case of the horizontal menu, you would also use.
ul li { float: left; }
to make it display horizontally.

Just some advice to make your functions just a tad better, though they're perfectly functional the way they are :)

Re: [simple] menu loading from mysql db

Posted: Tue Jun 21, 2011 11:41 pm
by runeqm
thanks for the advice i had never used functions much and i just thought i would see how i go at creating one