我有一个funcs.php文件,其中包含如下函数:
function fetchProductDetails($id)
{
global $mysqli;
$column = "id";
$data = $id;
$stmt = $mysqli->prepare("SELECT
id,
product_name,
price,
tags,
summary,
description
FROM products
WHERE
$column = ?
");
$stmt->bind_param("s", $data);
$stmt->execute();
$stmt->bind_result($id,$productName,$price,$tags,$summary,$description);
while ($stmt->fetch()){
$row = array('id' => $id, 'productName' => $productName, 'price' =>$price,'tags' => $tags, 'summary' => $summary, 'description' => $description);
}
$stmt->close();
return $row;
}
现在,当我在新页面上调用该函数时,它不会给出任何错误。但当我在其他页面上调用此函数时,会出现一个错误:
Call to a member function prepare() on a non-object in
为了调用该函数,我编写了以下代码:
include '../funcs.php';
//Product ID
$id = 1;
//Product details into a single variable..
$productDetails = fetchProductDetails($id);
//Product Name
$productName = $productDetails['productName'];
// Product Summary...
$productSummary = $productDetails['summary'];
//Product price..
$productPrice = $productDetails['price'];
//Product Description
$productDescription = $productDetails['description'];
在打印以下内容时,为什么会出现此错误。?为什么当我在另一页上写相同的代码时不会出错。?
在调用fetchProductDetails($id)
之前,代码中缺少$mysqli
的声明。你需要一条像一样的线路
$mysqli = new mysqli($host, $user, $password, $database);
其中传递给构造函数的变量是您的数据库凭据。