dongyidao1461 2015-08-31 04:18
浏览 8
已采纳

代码移动到函数时无法连接到数据库[重复]

This question already has an answer here:

I want to make a function that counts the total of user in the database.

$count = "SELECT COUNT(userid) FROM user ";
$run=mysqli_query($con,$count);
$result = mysqli_fetch_array($run);
echo $result[0];

The code above works fine. However, when I put it inside a function:

<?php
include("db.php");

function popo()
{
    $count = "SELECT COUNT(userid) FROM user ";
    $run=mysqli_query($con,$count);
    $result = mysqli_fetch_array($run);
    echo $result[0];
}
?>

<?php
popo();
?>

The following errors appear:

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\admin\includes\function.php on line 5

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\admin\includes\function.php on line 6

</div>
  • 写回答

2条回答 默认 最新

  • dongxianchu3541 2015-08-31 04:21
    关注

    $con doesn't exist inside the function, only outside it.

    You could either pass $con to the function like this:

    function popo($con)
    ...
    popo($con);
    

    or you could make it global (but this is not great style):

    function popo() {
      global $con;
      ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?