gpt4 book ai didi

php - 无法访问其他文件中的 mysqli 连接对象?

转载 作者:行者123 更新时间:2023-11-29 18:13:46 25 4
gpt4 key购买 nike

dbConnection.php

<?php
include_once('config.php');
$dbConnection = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
if($dbConnection->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
mysqli_set_charset($dbConnection, 'utf8');
?>

新闻.php

<?php
require_once('dbConnection.php');
function getNews($request){
$sql = "select * from news";
if (!$result = $dbConnection->query($sql)) {
die('There was an error running the query [' . $dbConnection->error . ']');
}

$news = array();
while ($row = $result->fetch_assoc() ){
$news[]=$row;
}

$result->free();
$dbConnection->close();
return $news;
}

$latestNews = getNews($_REQUEST);
echo json_encode($latestNews);
?>

我收到错误 undefined variable :dbConnection on line xx。有人可以帮我解决这个问题吗?

最佳答案

您收到此错误是因为您尝试在函数内访问此变量。

您应该将变量作为参数传递,如下所示:

function getNews($request, $dbConnection) {...}
$latestNews = getNews($_REQUEST, $dbConnection);

或者使用全局:

function getNews($request)
{
global $dbConnection;
...
}

关于php - 无法访问其他文件中的 mysqli 连接对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47195489/

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