简体   繁体   中英

mysql SELECT price range php

I would like to return rows matching the user input for price, ie from $ to $.

<form action="" method="post">
   <input class="price" name="p1" type="text"> 
   to 
   <input class="price" name="p2" type="text"><br>
   <input type="submit" name="sprice" value="go" >
</form>

Here is the select query. It doesn't return rows depending on the price range.

if (isset($_POST["sprice"]) && (!empty($_POST["p1"])) && (!empty($_POST["p2"]))){
    $p1 = $_POST["p1"];
    $p2 = $_POST["p2"];

    $paginate = new pagination($page
        , 'SELECT * FROM test where price BETWEEN "$p1" AND "$p2" ORDER BY id desc'
        , $options
    );

 }
'SELECT * FROM test where price BETWEEN "$p1" AND "$p2" ORDER BY id desc'

the above form not replacing variables, you need this

"SELECT * FROM test where price BETWEEN '$p1' AND '$p2' ORDER BY id desc"

http://php.net/manual/en/language.types.string.php#language.types.string.syntax.single

use the following code

         SELECT * FROM test where price BETWEEN '$p1' AND '$p2' ORDER BY id desc"
          SELECT * FROM test where price >=$p1 AND price<=$p2 ORDER BY id desc"

You can use AND and comparison operators to specify the range.

"SELECT * FROM test where price where price >= '$p1' AND price <= '$p2' ORDER BY id desc"

Just to ensure(Check) : Try the below code.

<?php

$host = "localhost"; // Host name 
$username = "----"; // Mysql username 
$password = "----"; // Mysql password 
$db_name = "------"; // Database name 

$conn = mysql_connect($host, $username, $password);
mysql_select_db($db_name, $conn) or die("cannot select DB");

$p1 = VALUE_To_CHECK_WITH_1; //$_POST["p1"];
$p2 = VALUE_To_CHECK_WITH_2; //$_POST["p2"];

$query = "SELECT * FROM test where price where price >= '$p1' AND price <= '$p2' ORDER BY id DESC";

//or you may use
// "SELECT * FROM test where price BETWEEN '$p1' AND '$p2' ORDER BY id desc"


$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
    $data[] = $row;
}

print_r($data);

?>

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