您好我正在学习如何使用php创建一个简单的mvc,但似乎在执行类函数内的查询时遇到了一些麻烦。
当我从类功能中取出代码时,它们工作正常。但是当代码在里面时它们不起作用。任何想法将不胜感激。
<?php
include_once("model/book.php");
class Model {
public function getBookList()
{
$conn=mysqli_connect("localhost","Ory4n","","test");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Title, Author, Description FROM books";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<h2 class="word">'.$row["Title"].'</h2>';
echo '<h4 class="word">'.$row["Author"].'</h4>';
echo '<p class="word">'.$row["Description"].'</p>';
}
} else {
echo "0 results";
}
} // close function
public function getBook($title)
{
getBookList();
}
}
?>
答案 0 :(得分:0)
总结评论......
<?php
class Model {
/**
* @return array Empty array in case of no results
*/
public function getBookList() {
$conn=mysqli_connect("localhost","Ory4n","","test");
if($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Title, Author, Description FROM books";
$result = $conn->query($sql);
$books = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$book = new stdClass();
$book->title = $row['Title'];
$book->author = $row['Author'];
$book->description = $row['Description'];
$books[] = $book;
}
}
return $books;
}
}
//Demo - how to use
$model = new Model();
$books = $model->getBookList();
foreach($books as $book) {
echo '<h2 class="word">'.$book->title.'</h2>';
echo '<h4 class="word">'.$book->author.'</h4>';
echo '<p class="word">'.$book->description.'</p>';
}
?>