【发布时间】:2020-08-10 01:30:03
【问题描述】:
我希望网页在单击搜索按钮后显示结果。目前,整个表格在页面加载时显示。 如果我从“Select * FROM users”中更改变量 $sql 的值,则搜索查询不再起作用
我正在使用 XAMPP,网页是 php 文件,数据库是 Mariadb
用户表
+--------+-------------+---------------+--------------------------+--------+
| ID | firstname | lastname | address | count |
| | | | | |
+--------------------------------------------------------------------------+
| 1 | john | doe |james street, idaho, usa | 2 |
| | | | | |
+--------------------------------------------------------------------------+
| 2 | cindy | smith |rollingwood av,lyn, canada| 1 |
| | | | | |
+--------------------------------------------------------------------------+
| 3 | rita | chatsworth |arajo ct, alameda, cali | 0 |
| | | | | |
+--------------------------------------------------------------------------+
| 4 | randy | plies |smith spring, lima, (peru)| 1 |
| | | | | |
+--------------------------------------------------------------------------+
| 5 | Matt | gwalio |park lane, (atlanta), usa | 2 |
| | | | | |
+--------------------------------------------------------------------------+
带有搜索栏的网页。
<?php
ini_set('memory_limit', '1042M');
$localhost = "localhost";
$username = "root";
$password = "";
$dbname = "samueldb";
$con = new mysqli($localhost, $username, $password, $dbname);
if( $con->connect_error){
die('Error: ' . $con->connect_error);
}
$sql = "SELECT * FROM users";
if( isset($_GET['btn']) ){
$name = mysqli_real_escape_string($con, htmlspecialchars($_GET['search']));
$sql = "SELECT * FROM 'users' WHERE 'firstname' ='$name'";
}
$result = $con->query($sql);
?>
<!DOCTYPE html>
<html>
<head>
<title>Find my search results</title>
<link href="css/templatemo-style.css" rel="stylesheet" />
<link href="css/font-awesome.min.css" rel="stylesheet" />
<link href="css/font-awesome.css" rel="stylesheet" />
<link href="css/bootstrap.css" rel="stylesheet" />
<link href="css/search-style.css" rel="stylesheet" />
</head>
<body>
<h2>List of students</h2>
<div class="search">
<input type="text" class="searchTerm" placeholder="What are you looking for?">
<button type="search" class="searchButton">
<i class="fa fa-search"></i>
</button>
</div>
</div>
<table class="table table-striped table-dark">
<tr>
<th>ID</th>
<th>First_Name</th>
<th>Address</th>
<th>Count</th>
</tr>
<?php
while($row = $result->fetch_assoc()){
?>
<tr>
<td><?php echo $row['ID']; ?></td>
<td><?php echo $row['firstname']; ?></td>
<td><?php echo $row['address']; ?></td>
<td><?php echo $row['count']; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</body>
</html>
【问题讨论】:
-
警告:您对SQL Injections 持开放态度,应该使用参数化的prepared statements,而不是手动构建查询。它们由PDO 或MySQLi 提供。永远不要相信任何形式的输入!即使您的查询仅由受信任的用户执行,you are still in risk of corrupting your data。 Escaping is not enough!