简体   繁体   English

php pdo fetch无法使用功能

[英]php pdo fetch not working with functions

Can anyone tell me where i am going wrong in this small php snippet 谁能告诉我在这个小的PHP代码段中我要去哪里了

config.php config.php

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

php in my html file 我的html文件中的php

$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... 现在由于某种原因这不起作用,现在我不太清楚php,只是学习了一些数据库集成所以请是否有人可以告诉我我错误地复制了什么...

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()函数的范围是外部变量在内部不可用,您需要将变量作为参数传递,例如:

mainMenu($q);

Please see more about Variable Scope 请查看有关可变范围的更多信息

Also, mysql_real_escape_string() is not required when outputting data. 另外,输出数据时不需要mysql_real_escape_string()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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