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 对于这个问题的代码运行
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败