如何在$connect
类中使用User
变量而不发送$connect
作为参数或在User类中定义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!';
答案 0 :(得分:0)
尝试 -
<?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!';