我有一个问题。我无法使用PHP从mysql数据库中获取记录。我在下面解释我的代码。
user.php的:
require_once ('../../include/dbconfig.php');
require_once ('common.php');
error_reporting(E_ALL);
ini_set('display_errors', '1');
$userClass=new CommonConnectorFuncs();
$redata=$userClass->insertUserRecordForSignup();
echo $redata;exit;
的common.php:
require_once ('../../include/dbconfig.php');
error_reporting(E_ALL);
ini_set('display_errors', '1');
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") ? "https" : "http";
$imagepath=$protocol. "://" . $_SERVER['HTTP_HOST']."/connector/upload/";
class CommonConnectorFuncs{
function __construct() {
}
// destructor
function __destruct() {
// $this->close();
}
public function insertUserRecordForSignup(){
$sql=mysqli_query($connect,"select * from cn_user_info order by user_id desc");
while ($row=mysqli_fetch_array($sql)) {
$data[]=$row;
}
return $data;
}
}
这里我试图通过课程获取记录和打印,但它抛出以下信息。
Notice: Undefined variable: connect in common.php on line 16
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in common.php on line 16
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in common.php on line 17
Notice: Undefined variable: data in common.php on line 20
这些查询在user.php
文件中正常工作但在common.php
文件中无效。请帮我解决此问题。
答案 0 :(得分:0)
正如评论中所提到的,这是一个范围问题。具体来说,$ connect不在范围内。
注意:未定义的变量:在第16行的common.php中连接 在任何地方都没有定义连接。
此外,它与错误状态完全相同,因为您错误地将参数传递给mysqli_query。假设$ connect是new mysqli()
在某个时刻生成的mysqli连接,它应该是:
$sql = "select * from cn_user_info order by user_id desc";
$result = mysqli_query( $connect,$sql) or die('Could not look up user information; ' . mysqli_error($connect))
希望它有所帮助!
答案 1 :(得分:0)
问题在于您尝试访问global
内的function
变量。
首先,请确保include
具有相关数据库连接的php文件。当您尝试访问全局变量时,有两种方法可以实现此目的。
方法1
在函数顶部创建一个global
变量。
global $connect;
但正如Qirel this comment所述,这是一种不好的做法,所以我建议下一步。
方法2
将连接传递给函数的参数。
public function insertUserRecordForSignup($connect){
$sql=mysqli_query($connect,"select * from cn_user_info order by user_id desc");
while ($row=mysqli_fetch_array($sql)) {
$data[]=$row;
}
return $data;
}
希望你觉得这很有用。
答案 2 :(得分:0)
通过在构造函数中解析它,使连接变量成为类的属性
require_once ('../../include/dbconfig.php');
require_once ('common.php');
error_reporting(E_ALL);
ini_set('display_errors', '1');
$userClass=new CommonConnectorFuncs($connect);
$redata=$userClass->insertUserRecordForSignup();
echo $redata;exit;
在你的班上,
class CommonConnectorFuncs{
var $Connection;
function __construct($connection) {
try{
if($connection != null){
$this->Connection = $connection;
}else{
throw new Exception('Connection is null. COuld not process further');
}
}catch(Exception $ex){
echo $ex->getMessage();
exit;
}
}
// destructor
function __destruct() {
// $this->close();
}
public function insertUserRecordForSignup(){
$sql=mysqli_query($this->Connection,"select * from cn_user_info order by user_id desc");
while ($row=mysqli_fetch_array($sql)) {
$data[]=$row;
}
return $data;
}
}