以下是我在SO的帮助下提供的代码。我试图能够在同一页面上实现$select
语句以及$search
语句。 $select
语句工作正常,但我不知道如何在用户使用代码中的表单进行搜索时调用$search
语句。有谁知道如何做到这一点,或者你可以重定向到一个关于表单如何与PHP交互的好教程?
<?php
require 'db/connect.php';
$select = $db->query("SELECT * FROM customers ORDER BY id DESC");
$search = $db->query("SELECT * FROM customers WHERE FName LIKE '%$_REQUEST[q]%' OR LName LIKE '%$_REQUEST[q]%' ORDER BY id DESC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="wrapper">
<h1>Customers</h1>
<p><a class="btn create" href="createcustomer.php">CREATE</a></p>
<?php
if (!$select->num_rows) {
echo '<p>', 'No records', '</p>';
}else{
?>
<table border="1" width="100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Phone</th>
<th>Alt Phone</th>
<th>Job Address</th>
<th>Billing Address</th>
<th>Email</th>
<th>Alt Email</th>
</tr>
</thead>
<tbody>
<?php
while ($row = $select->fetch_object()) {
?>
<tr>
<td><?php echo $row->FName;?></td>
<td><?php echo $row->LName;?></td>
<td><?php echo $row->Phone;?></td>
<td><?php echo $row->AltPhone;?></td>
<td><?php echo $row->JobAddress;?></td>
<td><?php echo $row->BillingAddress;?></td>
<td><?php echo $row->Email;?></td>
<td><?php echo $row->AltEmail;?></td>
<td><a class="btn read" href="viewcustomer.php?id=<?php echo $row->id; ?>">READ</a> <a class="btn update" href="editcustomer.php?id=<?php echo $row->id; ?>">UPDATE</a> <a class="btn delete" href="deletecustomer.php?id=<?php echo $row->id; ?>">DELETE</a></td>
</tr>
</tbody>
<tbody>
<?php
}
?>
</table>
<?php
}
?>
# Search form that needs tied to $search
<input type="text" name="q" /> <input type="submit" name="search" />
</div>
</body>
</html>
答案 0 :(得分:1)
您需要验证表单是否在您的php代码中发送:
<?php
require 'db/connect.php';
if(isset($_POST['q'])) {
$q = $_POST['q'];
$select = $db->query("SELECT * FROM customers WHERE FName LIKE '%$q%' OR LName LIKE '%$q%' ORDER BY id DESC");
} else {
$select = $db->query("SELECT * FROM customers ORDER BY id DESC");
}
?>
您需要更改代码才能添加表单
<form method="post">
<input type="text" name="q" /> <input type="submit" name="search" />
</form>
答案 1 :(得分:1)
我想'%$_REQUEST[q]%'
会给您一个问题,因为您想要访问$_REQUEST['q']
而不是$_REQUEST[q]
。
用'%" . $_REQUEST['q'] . "%'
替换它应该是一个好的开始。
但是你通常不想这样做,因为这段代码很容易被sql注入。
因此你应该使用引用函数:
$search = $db->query("SELECT * FROM customers WHERE FName LIKE " . $db->quote("%" . $_REQUEST['q'] . "%") . " OR LName LIKE " . $db->quote("%" . $_REQUEST['q'] . "%") . " ORDER BY id DESC");
您要做的下一件事是检查表单输入是否已设置并使用搜索结果而不是没有搜索参数的select语句:
if (isset($_REQUEST['q'])) {
$q = "%" . $_REQUEST['q'] . "%";
$select = $db->query("SELECT * FROM customers WHERE FName LIKE " . $db->quote($q) . " OR LName LIKE " . $db->quote($q) . " ORDER BY id DESC");
} else {
$select = $db->query("SELECT * FROM customers ORDER BY id DESC");
}