php - 如何在 PHP 类中使用 mysqli_query?

标签 php mysql database mysqli

我如何在 User 类中使用 $connect 变量而不发送 $connect 作为参数或定义 global $connect 在用户类中?

而我只想创建一个连接是

$connect = mysqli_connect('localhost', 'root', '1234', 'mydatabase');

错误

警告:mysqli_query() 期望参数 1 为 mysqli,第 9 行的 D:\xampp\htdocs\mateocode\index.php 中给出的 null

示例代码

<?php
    class User {    
        public $id;
        public $username;
        function __construct($user_id)
        {   
        $sql = "select id, username from user where id = '$user_id' limit 1";

        $result = mysqli_query($connect, $sql);    
        if(!$result) return false;

        if(mysqli_num_rows($result)>0){
            $data = mysqli_fetch_assoc($result);
            $this->id = $data['id'];
            $this->username = $data['username'];
        }else{ 
            return false; 
        }   
    }
}

$connect = mysqli_connect('localhost', 'root', '1234', 'mydatabase');

if($objUser = new User(1))
    echo $objUser->username;
else 
    echo 'There was an error or user not found!'; 

最佳答案

尝试 -

<?php
    class User {    
        public $id;
        public $username;
        function __construct($user_id, $connect)
        {   
        $sql = "select id, username from user where id = '$user_id' limit 1";

        $result = mysqli_query($connect, $sql);    
        if(!$result) return false;

        if(mysqli_num_rows($result)>0){
            $data = mysqli_fetch_assoc($result);
            $this->id = $data['id'];
            $this->username = $data['username'];
        }else{ 
            return false; 
        }   
    }
}

$connect = mysqli_connect('localhost', 'root', '1234', 'mydatabase');

if($objUser = new User(1, $connect))
    echo $objUser->username;
else 
    echo 'There was an error or user not found!';

关于php - 如何在 PHP 类中使用 mysqli_query?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28167764/

相关文章:

php - Ajax 响应上的 Jquery 事件

php - 在登录脚本中将 password_verify 放在哪里?

mysql - 计算表中的组,但如果 2 组中的任何记录相同,则仅将其视为一个组

.net - 监控数据库中的表

sql - 国际化的MySQL数据库设计

php - CakePHP 3.x 数据库迁移插件 : Is there a way to Change a table field?

php - 在 IBM i (AS400) DB2 中导入/导出 CSV

php - wkhtmltopdf 从文件随机空框生成 PDF

java - Prepared Statement 'setObject' 方法可以用于任何数据类型吗?

Python获取时差