简体   繁体   中英

php pdo fetch not working with functions

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM