简体   繁体   中英

Php search with multiple values

i try to make a search system which has multiple inputs. I tried to to select the data in query and that it supose to add the aditional data if it exist but it dont do that. i messed it up and dont know how to fix it. The data from my other file gets there. I checked it. Did anyone know what i did wrong?

<?php
    $connect= mysqli_connect("localhost", "root", "root", "website");
    $query = "SELECT * FROM data";
    $sort = " date DESC"
    if(isset($_GET["search"])){
        $keywordsearch = $connect->escape_string($_GET['search']);
        $query .= " WHERE name like '%$keywordsearch%'";

        if(isset($_GET['tag'])){
            $keywordtag = $connect->escape_string($_GET['tag']);
            $query .= " AND tag like '%$keywordtag%'";  
            $query .= " ORDER BY $sort";
        }
    }
    $result = mysqli_query($connect, $query);
    while($row = mysqli_fetch_array($result)){
        echo $row['name']."<br>";
    }
    ?>

This can be done by creating an array of the data passed in and using that array you can control all the other requirements to build a query and pass parameters using a Parameterised and bound query

$_GET = ['search'=> 'fluff', 'tag'=>'easy'];


$connect= mysqli_connect("localhost", "root", "root", "website");
$query = "SELECT * FROM data";
$sort = " ORDER BY date DESC";

if(isset($_GET["search"])){
    $query .= " WHERE name like ?";
    $vals[] = '%' . $_GET["search"] . '%';
}

if(isset($_GET['tag'])){
    $query .= " OR tag like ?";  
    $vals[] = '%' . $_GET["tag"] . '%';
}

$query .= $sort;

$types = str_repeat('s', count($vals));

$stmt = $connect->prepare($query);
$stmt->bind_param($types, ...$vals);
$stmt->execute();

$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC)){
    echo $row['name']."<br>";
}

RESULT:

easy peasy<br>
fluff fluff<br>

From your comment: problem is that i can input the tag variable and if the tag variable is something that is not included in the database it shows nothing

That is because you are using an AND rather than an OR in the query. I corrected that also

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM