[英]php show data from mysql
你好我有以下脚本
显示.php
<?php
include "db.php"; // <== db connection
include "sys.php"; //<== main system
// statment to show $result as table
?>
我需要正确的语句来读取我的表格数据并将其显示为表格
我有 1 个有 7 行的表:
username| name| age| etc
它们是大约 500 条记录,每页需要显示 20 条
如何建立正确的陈述?
首先,您需要使用 mysql 或 mysqli(推荐)从数据库中获取数据。 由于您希望将项目数限制为 20,因此明智的做法是在 sql 中添加限制条件,而不是稍后过滤掉项目,这对于性能至关重要。 最后简单地遍历数据,为数据库中的每一行生成一个新的表行。
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// remember to sanitize potential user input
$start = (int) (!empty($_GET['start']) ? $_GET['start'] : 0);
$end = (int) (!empty($_GET['end']) ? $_GET['end'] : 20);
$query = "SELECT username, name, age FROM users limit $start, $end";
if ($stmt = $mysqli->prepare($query)) {
/* execute statement */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($username, $name, $age);
?>
<table>
<tr>
<th>Username</th>
<th>Name</th>
<th>Age</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<?php
/* fetch values */
while ($stmt->fetch()) {
// do something with the fetched variables here
?>
<tr>
<td><?php echo htmlentities($username); ?></td>
<td><?php echo htmlentities($name); ?></td>
<td><?php echo htmlentities($age); ?></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<?php
}
/* close statement */
$stmt->close();
?></table><?php
}
/* close connection */
$mysqli->close();
?>
您需要使用某种分页库。
查看PHP Sense 的分页示例,找出适合您的方法!
需要更多信息(db.php 的内容以及 sys.php 的用途)。
假设 db.php 包含一个 class 用于访问您的数据库,您需要创建一个数据库实例并使用您的连接信息对其进行初始化。 以下不一定反映您的设置或 db class 结构。
$db = new Db();
$host = "localhost";
$username = "bob";
$dbname = "bobs_db";
$password = "opensesame";
$db->connect( $host, $dbname, $username, $password );
如果成功,则运行查询:
$query = "SELECT username, name, age FROM users";
$db->query( $query );
$users = $db->fetch_all();
// Go through users using a foreach
为了每页显示 20 个用户,您需要使用 MySQL 的 LIMIT 关键字进行所谓的分页。 一旦您提供更多信息,将在此答案中添加更多内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.