gpt4 book ai didi

php - 在非对象上调用成员函数 query()

转载 作者:搜寻专家 更新时间:2023-10-30 23:39:15 24 4
gpt4 key购买 nike

我正在尝试让 php 简化我的数据库连接,以便我可以修改代码的一个区域并影响整个程序。这是我所拥有的:

PAGE: rdpa.php(模块页面

/**************************/
/* Create System Settings */
/**************************/

/* Database Connection Settings */
$_SESSION['servername'] = "localhost";
$_SESSION['mysql_username'] = "username";
$_SESSION['mysql_password'] = "password";
$_SESSION['dbname'] = "mydb";

//Turn on Error Report. True = On / False = Off
//ErrorReporting(false);

//Display Error.kfkg
function ErrorReporting($ErrOn){
if ($ErrOn == true) {
//Show Error
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
}
}

/**************************************
Open Database Connection Function.
***************************************/

class db_class {

function db_conn() {

global $conn;
global $mysqli;
$conn = new mysqli($_SESSION['servername'], $_SESSION['mysql_username'], $_SESSION['mysql_password'], $_SESSION['dbname']);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);

// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}

//return db_conn;
}

}

页面:testdb3.php

<?php

//Included file.
include 'modules/rdpa.php';

error_reporting(-1);
ini_set('display_errors', 'On');

//Access our class.
$db_Class = new db_Class;
$conn = ($db_Class->db_conn());

//connect to the database.
$sql = "SELECT id, region FROM tbl_region;";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {

echo '<td width="1"><label for="delete">
<input type="radio" name="region" id="region" value="'.$row["id"].'">
</label></td>';

echo '<td align="left" valign="top"><p>'.$row["region"].'</p></td></tr>';
}
}


?>

当我运行 testdb3.php 时出现以下错误:

fatal error :在第 15 行调用 C:\websites\rdpa\testdb3.php 中非对象的成员函数 query()

这是第 15 行:

//connect to the database.
$result = $conn->query($sql);

有人可以告诉我我在这里做错了什么吗?

最佳答案

将您的 rdpa.php 页面更改为

class db_class {

function db_conn() {

global $conn;
global $mysqli;
$conn = new mysqli($_SESSION['servername'], $_SESSION['mysql_username'], $_SESSION['mysql_password'], $_SESSION['dbname']);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);

// Test if connection succeeded
if (mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
}
return $conn; //return connection string
}

} //this is missing in your code

您需要从函数返回连接字符串。现在你在 if 循环中返回 $conn 即如果发生错误然后返回连接这就是你正在做的。

请使用一些IDE来编码。您的代码中缺少 class

关于php - 在非对象上调用成员函数 query(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37130031/

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