gpt4 book ai didi

php - 将 mysql 连接作为参数传递时出错

转载 作者:行者123 更新时间:2023-11-30 22:17:37 24 4
gpt4 key购买 nike

我正在尝试使用 PHP 和 mysql 构建一个基本 API,并且根据 url 路径,使用了不同的数据库表,因此需要建立连接。但我不断收到此错误:

Fatal error: Call to a member function prepare() on a non-object in....line 6

仪表板.class.php:

class dashboard {
public function getData($conn) {
// Get latest status
$stmt = $conn->prepare("SELECT status FROM status_archive ORDER BY datetime DESC LIMIT 1 ");
$stmt->execute(); //line 6
$stmt->bind_result($status);
$stmt->fetch();
($status == '1' ? $status = 'up' : $status = 'down');
$stmt->close();
return $status;
}
}

创建数据库连接的函数:

function db_connection($type) {
$db = $type.'_db';
syslog(LOG_INFO, 'DB: '.$db);
// Check to see if a development or production server is being used
if (strpos(getenv('SERVER_SOFTWARE'), 'Development') === false) {
$conn = mysqli_connect(null,
getenv('PRODUCTION_DB_USERNAME'),
getenv('PRODUCTION_DB_PASSWORD'),
$db,
null,
getenv('PRODUCTION_CLOUD_SQL_INSTANCE'));
} else {
$conn = mysqli_connect(getenv('DEVELOPMENT_DB_HOST'),
getenv('DEVELOPMENT_DB_USERNAME'),
getenv('DEVELOPMENT_DB_PASSWORD'),
$db);
}
// Check if successful connection to database
if ($conn->connect_error) {
die("Could not connect to database: $conn->connect_error " .
"[$conn->connect_errno]");
}

return $conn;
}

这是启动一切的文件末尾的代码:

$path_array = explode("/", parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH));
$conn = db_connection($path_array[3]);
include 'classes/dashboard.class.php';
$dashboard = new dashboard;
$results = $dashboard->getData($conn);
echo json_encode($results, JSON_PRETTY_PRINT);

最佳答案

mysqli_connect 可以返回假值。
您应该使用 OOP 样式(new mysqli)或检查 $conn:

$conn = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');

if (!$conn) {
die('Connection error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}

php.net - 请参阅“程序样式”示例。

关于php - 将 mysql 连接作为参数传递时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37731369/

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