dongpa6867 2014-02-05 22:59
浏览 57
已采纳

php mysqli数据库连接失败?

Goodday,

I get an strange error.

this is my code:

<?php
$con=mysqli_connect("localhost","root","","testdatabase");

class database{
    public function select($tableName){
        $result = mysqli_query($con,"SELECT * FROM ".$tableName);       
    }       
}

$database = new database();
?>

The error message is that $con is an undefined variable. But i define $con on line number 2?

when i var_dump con it also says NULL.

What am i doing wrong?

  • 写回答

4条回答 默认 最新

  • duanmuybrtg1231 2014-02-05 23:04
    关注

    If you want to access to your $con var in a method or function, you have to globalize it inside your code :

    public function select($tableName){
        global $con;
        $result = mysqli_query($con,"SELECT * FROM ".$tableName);       
    }
    

    But you shouldn't do that, globals are evil !

    This is how your code should be :

    <?php
    class database{
        protected $con;
    
        public function __construct($host, $user, $password, $dbname){
            $this->con = mysqli_connect($host, $user, $password, $dbname);
        }
    
        public function select($tableName){
            $result = mysqli_query($this->con,"SELECT * FROM ".$tableName);       
        }       
    }
    
    $database = new database("localhost", "root", "", "testdatabase");
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

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