gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:50:56 27 4
gpt4 key购买 nike

我如何在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com