大家好日子。我试图运行我的查询,但每次我尝试运行它,它会给我这种错误:在非对象上调用成员函数fetchAll()。我真的不知道这个问题是什么以及它是如何引起的。
这是我的代码。
bookReserve.php
<?php
session_start();
include_once "../styles/header-menu-out.php";
include_once "dbconnection.php";
function __autoload($class){
include_once("../main/".$class.".php");}
$code = new codex_books();
$sname = $_POST['sname'];
$sid = $_POST['sid'];
$id = $_POST['id'];
$title = $_POST['title'];
$author = $_POST['author'];
$isbn = $_POST['isbn'];
$publisher = $_POST['publisher'];
$language = $_POST['language'];
$genre = $_POST['genre'];
$quantity = $_POST['quantity'];
$date_to_be_borrow = $_POST['date_to_be_borrow'];
$statement = $code->bookreserve1($id,"book_info");
if(isset($_POST['reserve']))
{
while($row = $statement->fetchAll(PDO::FETCH_ASSOC))
{
$oldstock=$row['quantity'];
}
$newstock = $oldstock-$quantity;
$code->bookreserve2($newstock,"book_info");
$code->bookreserve3($q,"reserve_list");
}
else
echo "<script type='text/javascript'>
alert('Successfully Reserved.');
window.location='bookReservelist.php';
</script>";
?>
codex_books.php
public function bookreserve1($id, $table)
{
$q = "SELECT * FROM $table WHERE id = :id";
$stmt = $this->con->prepare($q);
$stmt->execute(array(':id'=>$id));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result;
}
你能帮助我解决这个问题并让我理解外行人的这个错误吗?我是新来的。希望你能理解。感谢
答案 0 :(得分:1)
试试这个
public function bookreserve1($id, $table)
{
$q = "SELECT * FROM $table WHERE id = :id";
$stmt = $this->con->prepare($q);
$stmt->execute(array(':id'=>$id));
//fetchAll gets all rows found by query, as an array of rows.
//In your code $result = $stmt->fetch() returned only the first row, as ann associative array.
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
和
function __autoload($class) {include_once("../main/".$class.".php");}
$code = new codex_books();
$sname = $_POST['sname'];
$sid = $_POST['sid'];
$id = $_POST['id'];
$title = $_POST['title'];
$author = $_POST['author'];
$isbn = $_POST['isbn'];
$publisher = $_POST['publisher'];
$language = $_POST['language'];
$genre = $_POST['genre'];
$quantity = $_POST['quantity'];
$date_to_be_borrow = $_POST['date_to_be_borrow'];
$result = $code->bookreserve1($id,"book_info");
if(isset($_POST['reserve']))
{
//Iterate over the array of rows.
foreach($result as $row)
{
$oldstock=$row['quantity'];
}
$newstock = $oldstock-$quantity;
$code->bookreserve2($newstock,"book_info");
$code->bookreserve3($q,"reserve_list");
}
else {
echo "<script type='text/javascript'>alert('Successfully Reserved.');window.location='bookReservelist.php';</script>";
}
?>
在您的代码中,$statement
分配的$code->bookreserve1
变量是$stmt->fetch
返回的第一行,它是一个数组类型而不是PDO语句对象。
这就是调用$statement->fetchAll()
导致错误的原因。那时$ statement是一个数组。