首先,我很感激my question last week给我的帮助,但我仍然无法理解这一点。
当我在搜索框中输入单词或术语时,由以下代码处理......
<?php
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT ID, FirstName, LastName FROM `table` LIMIT 0, 30 ";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result)>0) {
// output data of each row
while($row=mysqli_fetch_assoc($result)) {
echo "ID: " . $row["ID"]. " - Name: " . $row["FirstName"]. " " . $row["LastName"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
我从SQL表中列出了所有可能的结果。
那么,如何将结果限制为最终用户输入的结果?我知道我应该使用LIKE或WHERE语句。
如果有帮助,我正在建立一个医疗专业人员数据库,他们的诊所名称和地点。
答案 0 :(得分:1)
假设您的表单如下所示:
<form action="" method="post">
Search: <input name="search" type="text">
</form>
您可以按如下方式扩展SQL:
$sql = "SELECT ID, FirstName, LastName FROM `table` ";
if (isset($_POST['search'])) {
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql .= " WHERE FirstName LIKE '%$search%'
OR LastName LIKE '%$search%' ";
}
$sql .= " LIMIT 0, 30 ";
$result = mysqli_query($conn, $sql);
// ... etc.
要清楚,“......等”表示您的输出代码保持原样:
if (mysqli_num_rows($result)>0) {
// output data of each row
while($row=mysqli_fetch_assoc($result)) {
echo "ID: " . $row["ID"]. " - Name: " . $row["FirstName"]. " " . $row["LastName"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
答案 1 :(得分:-1)
$sql1=mysqli_query("SELECT*FROM table ORDER BY id DESC LIMIT 1");
$result1=mysqli_fetch_array($sql1);