简体   繁体   English

在PHP MySQL数据库中搜索价格

[英]Search for prices in PHP MySQL database

I have code that searches for cars depending on your price range: 我有根据您的价格范围搜索汽车的代码:

$category = "SELECT * FROM tbl_listings WHERE price between '$c[0]' AND '$c[1]'"; 

For some reason, that code doesn't work perfectly. 由于某种原因,该代码无法完美运行。 It showed me a couple cars in the right range, but also showed one that is 200,000 when I was searching between 5,000 and 20,000. 它向我展示了几辆合适的汽车,但当我搜索5,000至20,000之间时,也向我展示了20万辆。

Also, what is a good way to search when some cars have a price with a dollar sign in the database and some have commas? 此外,当某些汽车的价格在数据库中带有美元符号的价格而某些汽车带有逗号时,什么是搜索的好方法呢? The search form is not returning anything with a dollar sign or commas. 搜索表单不会返回带有美元符号或逗号的任何内容。

Stop storing prices as strings? 停止以字符串形式存储价格? A price is typically stored as one of two types: 价格通常存储为以下两种类型之一:

  • integer: number of cents 整数:美分
  • float: dollars and cents, but be sure to set the number of decimal places to 2 float:美元和美分,但请务必将小数位数设置为2

One doesn't generally store prices as strings (like "$14,999.99") in the database because you can't do range queries, like the one you're trying to do now. 人们通常不会在数据库中以字符串形式存储价格(例如“ $ 14,999.99”),因为您不能像现在尝试的那样进行范围查询。

You also can't do arithmetic, like a query that totals the prices of a particular subset of cars. 您也无法执行算术运算,例如对特定汽车子集的价格进行总计的查询。

If the data you're pulling in has formatted strings like this, use NumberFormatter::parseCurrency() to get a float from the string you're given before shoving it in the DB. 如果您要提取的数据具有这样的格式化字符串,请在将其推入数据库之前,使用NumberFormatter :: parseCurrency()从给定的字符串中获取浮点数。 http://php.net/manual/en/numberformatter.parsecurrency.php http://php.net/manual/en/numberformatter.parsecurrency.php

Your statement about 您关于以下内容的声明

some cars have a price with a dollar sign in the database and some have commas 在数据库中,有些汽车的价格带有美元符号,而有些则带有逗号

makes me think the datatype in the database are not numeric datatype. 让我觉得数据库中的数据类型不是数字数据类型。 This can be an issue, even provided that your $c[0] is correctly the lower bound and $c[1] is the upper bound. 即使您的$c[0]正确地是下界而$c[1]是上限,这也可能是一个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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