我正在尝试使用CRUD PDO系统从数据库中获取/读取一些数据。
我知道以前可能已经问过这个问题,但是我发现的其他主题的答案似乎对我没有帮助。
错误:在第11行上调用未定义的方法DB :: prepare()。 我已经在注释行上标记了它(Student.php文件)。
我为数据库(DB.php)和学生表(Student.php)创建了一个单独的类。
数据库名称为:db_student, 表名称是:tbl_student
config.php
<?php
define('DB_HOST','localhost');
define('DB_NAME','db_student');
define('DB_USER','root');
define('DB_PASS','');
?>
DB.php
<?php
include "config.php";
class DB {
private static $pdo;
public static function connection() {
if (!isset(self::$pdo)) {
try {
self::$pdo = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS);
} catch (PDOException $e) {
echo $e->getMessage();
}
}
return self::$pdo;
}
public static function prepare($sql) {
return self::connection()->prepare($sql);
}
}
?>
Student.php
<?php
include "DB.php";
class Student {
private $table = 'tbl_student';
public function readAll() {
$sql = "select * from $this->table";
$stmt = DB::prepare($sql); //this line gives the fatal error
$stmt->execute();
return $stmt->fetchAll();
}
}
?>
接口/输出文件 index.php
<?php include "inc/header.php"; ?>
<?php include "classes/Student.php"; ?>
<?php
$user = new Student();
?>
<section class="mainleft">
<form action="" method="post">
<table>
<tr>
<td>Name: </td>
<td><input type="text" name="name" required="1"/></td>
</tr>
<tr>
<td>Department: </td>
<td><input type="text" name="name" required="1"/></td>
</tr>
<tr>
<td>Age: </td>
<td><input type="text" name="name" required="1"/></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="submit" value="Submit"/>
<input type="reset" value="Clear"/>
</td>
</tr>
</table>
</form>
</section>
<section class="mainright">
<table class="tblone">
<tr>
<th>No</th>
<th>Name</th>
<th>Department</th>
<th>Age</th>
<th>Action</th>
</tr>
<?php
foreach ($user->readAll() as $key => $value) {
?>
<tr>
<td><?php $value['id'] ?></td>
<td><?php $value['name'] ?></td>
<td><?php $value['department'] ?></td>
<td><?php $value['age'] ?></td>
<td>
<a href="">Edit</a> ||
<a href="">Delete</a>
</td>
</tr>
<?php } ?>
</table>
</section>
<?php include "inc/footer.php"; ?>
执行时收到错误消息“调用未定义的方法db :: prepare()”;
我正在看的东西可能很简单,但是真的很感谢您的帮助。