下面是一个比较简单的连接数据库并在网页上显示查询数据的一个例子,同时我把它结合了表单一起,即通过输入主键id来获取相对应的表格内容,下面是代码:
<html>
<head>
<title>我的第一个php数据库操作网页</title>
</head>
<body>
<?php
$iderror="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo " <div style='text-align:left'> ";
echo " <table border='1'> ";
echo " <tr><th>id</th>";
echo " <th>firstname</th>";
echo " <th>lastname</th>";
echo " <th>email</th>";
echo " </tr>";
if (empty($_POST["id"])) {
$iderror="编号不能为空";
} else {
//连接数据服务器
$conn=mysqli_connect("localhost","root","xxxxxxx","mydb");
if (!$conn) {
die ("数据连接失败!" . mysqli_connect_error());
}
//查询数据
$sql="SELECT id,firstname,lastname,email FROM MyGuests WHERE id={$_POST["id"]}";
$result=mysqli_query($conn,$sql);
//快速获取数据的条数,不用通过查询所有条数
$count=mysqli_query($conn,"SELECT COUNT(*) FROM MyGuests");
$num1=mysqli_fetch_array($count,MYSQLI_NUM);
echo "<h3>下面是查询表格结果,总数据条数为:" . $num1[0]. "</h3>";
$num=mysqli_num_rows($result);
for ($i=0;$i<$num;$i++) {
$row=mysqli_fetch_assoc($result);
$sid=$row["id"];
$sfirtname=$row["firstname"];
$slastname=$row["lastname"];
$semail=$row["email"];
echo "<tr><td>$sid</td>
<td>$sfirtname</td>
<td>$slastname</td>
<td>$semail</td>";
}
}
}
echo "</table>";
echo "</div>";
?>
<div style="text-align:left">
<p>输入你要获取的用户资料的id</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
编号:<input type="text" name="id">
<span style="color:red"> <?php echo $iderror;?></span>
<input type="submit" value="提交">
</form>
</div>
</body>
</html>
image.png
image.png
网友评论