【发布时间】:2017-03-09 11:47:43
【问题描述】:
我创建了一个 db 类,它有一个方法来处理与数据库的连接。
现在我在其他脚本中使用此方法从 SQL DB 中获取数据并显示在 HTML 表中。
错误信息:conn = new mysqli($this->_host, $this->_username, $this->_psw, $this->_dbName); if ($this->_conn->connect_error){ die("连接失败:" . $this->_conn->connect_error); } } 公共函数 getCon(){ 返回 $this->_conn; } } ?> 致命错误:未捕获错误:在 D:\XAMP\htdocs\telepol\userInfo.php:5 中找不到类 'db' 堆栈跟踪:#0 D:\XAMP\htdocs\telepol\userInfo.php(43): showData( ) #1 {main} 在第 5 行的 D:\XAMP\htdocs\telepol\userInfo.php 中抛出
db.php
<? php
class db{
private $_conn;
private $_host = "localhost";
private $_username = "root";
private $_psw = "";
private $_dbName = "users";
public function __construct(){
$this->_conn = new mysqli($this->_host, $this->_username, $this->_psw, $this->_dbName);
if ($this->_conn->connect_error){
die("Connection failed: " . $this->_conn->connect_error);
}
}
public function getCon(){
return $this->_conn;
}
}
?>
userInfo.php - 这个脚本将在 HTML 表格中显示数据
<?php
require_once 'classes/db.php';
function showData(){
$conn = new db();
$br = 1; //br is used to displat the number of each row in the table.
$userQuery = "SELECT* FROM users";
$result = $conn->getCon()->query($userQuery);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<tr> <td>" .$br ."</td> <td>" .$row["first_name"] ."</td> <td>" .$row["last_name"] ."</td> <td>" .$row["nickname"] ."</td> <td>" .$row["user_id"] ."</td> <br>" ;
$br ++;
}
}
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Users Info</title>
<!-- adding JS scripts -->
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<!-- adding css -->
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<!-- my CSS -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<table class="table table-striped table-bordered table-hover table-sm">
<thead class="thead-default">
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nickname</th>
<th>User ID</th>
</tr>
</thead>
<?php showData(); ?>
</table>
</body>
</html>
【问题讨论】:
-
您有错字,因此您的脚本未被识别为 php:
<? php应为<?php。这就是为什么您在构造函数中第一个>登录后看到您的代码回显的原因。在浏览器的源代码中,您将看到完整的 db 脚本。 -
谢谢!这是一个错字...花了 4 个小时试图修复一个错字。现在我收到此消息:致命错误:未捕获错误:调用 D:\XAMP\htdocs\telepol\userInfo.php:16 中的未定义方法 db::close() 堆栈跟踪:#0 D:\XAMP\htdocs\telepol \userInfo.php(43): showData() #1 {main} throw in D:\XAMP\htdocs\telepol\userInfo.php on line 16 你能告诉我如何解决吗?
-
已修复。我做了一个关闭连接的方法。