我在表1中有两个coulms是name和lastname,如果我使用name和lastname搜索全名,那么我有一个搜索输入,那么结果不可用 here is database structure
,输入代码为
<form class="form-inline" action="searchfrnd.php" method="GET">
<input style="margin-top:20px;" type="search" class="form-control" name="frnd_search" placeholder="Search your Friends">
</form>
和php代码是
$frnd_name=$_GET['frnd_search'];
$sql="select name,lastname,username,email from user where name='$frnd_name' or lastname='$frnd_name' or username='$frnd_name' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "".$row['name']." ".$row['lastname']."<br>"; }}
答案 0 :(得分:0)
尝试此查询:
SELECT
name, lastname, username, email
FROM
user
WHERE
CONCAT('%',name,'%') LIKE '$frnd_name' OR
CONCAT('%',lastname,'%') LIKE '$frnd_name' OR
CONCAT('%',username,'%') LIKE '$frnd_name'
它会在表单输入中查找name
,lastname
和username
。这远非完美,但是你想做它。
请不要忘记代码的安全性,它是不存在的。
答案 1 :(得分:0)
$frnd_name = trim(preg_replace( "/[ ]+/", " ", $_GET['frnd_search'] ) );
$arr = explode(" ", $frnd_name, 2);
if(!empty($arr[1]))
$sql_where = "name LIKE '%".$arr[0]."%' AND lastname LIKE '%".$arr[1]."%'";
else
$sql_where = "name LIKE '%".$arr[0]."%' OR lastname LIKE '%".$arr[0]."%'";
$sql = "SELECT name,lastname,username,email FROM user WHERE ".$sql_where;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "".$row['name']." ".$row['lastname']."<br>"; }}