视图文件
<?php
require('OrderModel.php');
session_start();
if(!isset($_SESSION['orderModel'])){
$newModel = new OrderModel();
$_SESSION['orderModel'] = $newModel;
} else{
$newModel = $_SESSION['orderModel'];
}
$newModel->addToBasket(1, 30);
echo $newModel->getItemName($newModel->basket[0][0]);
?>
OrderModel文件(简化)
class OrderModel{
public $basket;
public $orderDate;
public $orderTime;
public $sent;
public $dbc;
public $customerOrderID;
public function __construct()
{
$this->dbc = require_once('../../db/config.php');
$this->basket = [];
}
public function addToBasket($itemNumber, $itemQuantity){
array_push($this->basket, [$itemNumber, $itemQuantity]);
}
public function getItemName($itemNum){
$query = "SELECT ItemName FROM item WHERE ItemID = $itemNum;";
$r = mysqli_query($this->dbc, $query); //Line 31
if($r){
return mysqli_fetch_row($r)[0];
}else{
echo mysqli_error($this->dbc); //Line 35
}
}
我可以确认config.php文件肯定是正确配置并正在与数据库通信。无论如何,代码是:
<?php
define ('username', 'root');
define ('password', 'root');
define ('server', '127.0.0.1');
define ('database', 'alberto');
$dbc = mysqli_connect(server, username, password, database) OR DIE ('Could not connect to MySQL: ' . mysqli_connect_error());
mysqli_set_charset($dbc, 'utf8');
return $dbc;
?>
我从视图文件中收到以下错误消息:
警告:mysqli_query():无法在第31行的D:\ UniServerZ \ www \ alberto \ app \ models \ OrderModel.php中获取mysqli
警告:mysqli_error():无法在第35行的D:\ UniServerZ \ www \ alberto \ app \ models \ OrderModel.php中获取mysqli
我怀疑错误与会话有关,但我似乎无法从目前发布的帖子中找到任何答案。
请劝告。谢谢。
答案 0 :(得分:1)
Barmar是正确的,$ this-&gt; dbc不是有效的mysqli对象。您正在将require_once与函数一起使用。使config.php成为一个类,并从那里建立数据库连接。请参阅此处,了解我所指的内容。 https://gist.github.com/jonashansen229/4534794