0

Can anyone tell me where i am going wrong in this small php snippet

config.php

$sql = "SELECT * FROM sidemenu;";
$q = $conn->query($sql);

php in my html file

$q->setFetchMode(PDO::FETCH_NUM);
while($r = $q->fetch()){
    echo "
    <li>
       <a class='gn-icon ".mysql_real_escape_string($r[0])."'>".mysql_real_escape_string($r[1])."
       </a>
    </li>";
}

Now this snippet works and as expected generates the list items for me from the database. But now when i try something like this

$q->setFetchMode(PDO::FETCH_NUM);
function mainMenu(){
while($r = $q->fetch()){
    echo "
    <li>
       <a class='gn-icon ".mysql_real_escape_string($r[0])."'>".mysql_real_escape_string($r[1])."
       </a>
    </li>";
}
}
mainMenu();

Now this for some reason doesnt work, now i do not know php very clearly, just learned some database integration so please if anyone can tell what did i copied wrongly...

4

1 回答 1

0

This is because of the scope of the mainMenu() function that variables outside are not available inside, you need to pass variables as parameters such as:

mainMenu($q);

Please see more about Variable Scope

Also, mysql_real_escape_string() is not required when outputting data.

于 2013-08-31T20:22:31.487 回答