[simple] menu loading from mysql db

Written something you are proud of, post it here.
Post Reply
runeqm
Posts: 2
Joined: Tue Jun 21, 2011 2:25 am

[simple] menu loading from mysql db

Post 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
Tino
Posts: 360
Joined: Thu May 05, 2011 8:55 pm
Location: The Netherlands

Re: [simple] menu loading from mysql db

Post 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 :)
Please check out my CodeCanyon items.
runeqm
Posts: 2
Joined: Tue Jun 21, 2011 2:25 am

Re: [simple] menu loading from mysql db

Post 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
Post Reply