donglaogu3788 2015-07-12 04:01
浏览 20

无法使搜索逻辑在PHP中工作

So I'm trying to get a form with multiple value to work. I have like a min price range, max, area, city, and a search query for words. I've created separate "blocks" to check for each then get results, and I plan or merging the arrays together. Is this a good way to proceed? Here's what I got for example.

//Get post response
if(isset($_POST['query']) && isset($_POST['price1']) && isset($_POST['price2']) && isset($_POST['city']) && isset($_POST['area'])){
    $query = $_POST['query'];
    $price1a = $_POST['price1'];
    $price2a = $_POST['price2'];
    $city = $_POST['city'];
    $area = $_POST['area'];
}

//Make sure price is INT
$price1 = (int)$price1a;
$price2 = (int)$price2a;

echo $price1;

//Check to see which fields are empty
if(empty($query) && empty($price1) && empty($price2) && empty($city) && empty($area)){
    //User didn't bother entering anything, just return everything
    $stmt = $con->prepare("SELECT * FROM wp_posts");
    $stmt->execute();

    //Return as JSON string for parsing via front
    $json = json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
    echo $json;
}

//Price range for two INT
if(!empty($price1) || !empty($price2)){
    $stmt = $con->prepare("SELECT * FROM wp_posts WHERE price BETWEEN :price1 AND :price2");
    $stmt->bindValue(':price1', $price1);
    $stmt->bindValue(':price2', $price2);
    $stmt->execute();

    $json = json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
    echo $json;
}

//Price range for one INT, no max
if(!empty($price1) && empty($price2)){
    //Only price two is empty, therefore no max, so set a large number
    $max = 100000000;
    $stmt = $con->prepare("SELECT * FROM wp_posts WHERE price BETWEEN :price1 aND :price2");
    $stmt->bindValue(':price1', $price1);
    $stmt->bindValue(':price2', $max);
    $stmt->execute();

    $json = json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
    echo $json;
}

This is only a small part, but the two lower if statements show the min and max price. I was planning on getting those two results then merging the JSON. Will this work? Any better way of a "multi input search"?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 一直显示正在等待HID—ISP
    • ¥15 Python turtle 画图
    • ¥15 关于大棚监测的pcb板设计
    • ¥15 stm32开发clion时遇到的编译问题
    • ¥15 lna设计 源简并电感型共源放大器
    • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
    • ¥15 Vue3地图和异步函数使用
    • ¥15 C++ yoloV5改写遇到的问题
    • ¥20 win11修改中文用户名路径
    • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入