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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度