Search for prices in PHP MySQL database - php

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.
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
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.
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. 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.

Related

SQL BETWEEN prices stored as string

I'm running into a problem here. I'm storing prices in my database as a string in the following format: 14.500,00 and 199,95. Sometime later I created this range slider so the users can filter on price as you can see in the provided image. For this to work, I needed to write a new query so I was thinking of a BETWEEN in SQL but this doesn't work on strings. Any ideas to filter on price with a range slider in SQL?
BETWEEN does work on strings. It works just fine -- with the strings ordered alphabetically.
Your problem is that BETWEEN on strings doesn't follow the numeric ordering. Well, that is normal. If I'm speaking French, I wouldn't expect an English speaker to understand me. The same with types. If I use BETWEEN on strings, then I expect the comparisons to be string-based, not numeric. (The same is true of dates, by the way.)
Fix your data so the values are stored as numeric/decimal values. These are numbers with a fixed number of decimal places, exactly what is needed for monetary values.
In most databases, you will need to get rid of the dollar sign. Something like this should work:
update t
set price = replace(price, '$', '');
alter table t alter column price numeric(10, 2); -- or whatever is appropriate
The exact syntax might vary, depending on the database.

What SQL numeric data for non floating price?

I am having an issue on choosing the right numeric data for my price as my country currency do not use floating point.
Example: in my country currency we do not use this- 12700.58-
example of our price: 127,000 (which is hundred twenty seven thousand) for us.
So which sql numeric data type..i should use?
Thanks
First of all FLOAT/DOUBLE are non-exact datatypes so you should avoid it. Better to use DECIMAL/NUMERIC because they are accurate datatypes.
In you example(only whole numbers) I would use simple INT to store price:
CREATE TABLE tab(price INT UNSIGNED);
INSERT INTO tab VALUES (120000), (10);
The value with thousand separator 127,000 is only presentation matter and it should be done in application layer. If you still need to format it in database use:
SELECT FORMAT(price,0) AS formatted_price
FROM tab;
SqlFiddleDemo

Mysql, the last decimal zero disappears in Float data type for product prices

So I have a mysql database in my PhpMyAdmin which stores all the information about a big list of products. The name, description, the image file name and the price. So here is the case, some products have decimal numbers in their price so I set the datatype for productprice from int to float. But some products cost for instance, 199.90, as I enter that value in the table it receives it and stores it as 199.90 just as I want it to. But when I output the price on the website which I do with php it only outputs the number 199.9 as you can see the last zero is missing. Even though the two numbers are of the same value. 199.9 looks much less appealing than 199.90, and I hope that is understandable. So, what am I supposed to do?
You can use number formatting in PHP:
$Text = number_format($Amount,$Decimals,$DecimalSeperator,$ThousandsSeperator);
But remember that floats are not always the best type for storing prices. Normally prices are stored in cents in integers. The answer to the sum 100 - 50 is a definate 50, but the answer to 1.00 - 0.50 might be 0.499999999999999. This is just a simple example, it gets worse with more complicated calculation. A float is ok, as long as storing a price is the only thing you do. See also: Best data type to store money values in MySQL

PHP processing user-friendly formatted prices to standard floats

I have a form in which users can enter prices for items. Ideally I want the user to be able to add prices in whatever method feels best to them and also for readability. I then need to convert this to a standard float so that my web service can calculate costs etc.
The part I'm struggling with is how to take the initial sting/float/int of currency and convert it into a float.
For example:
UK: 1,234.00
FRA: 1 234,00
RANDOM: 1234
RANDOM2: 1234.00
All of those have slightly different formats.
Which I would want to store as:
1234.00
I will then store the result in MySQL database as a DECIMAL.
Any help would be great.
Assuming you're using MySQL, use the DECIMAL or NUMERIC type are the correct types used for storing currency.
Float's are susceptible to rounding errors and have a limited precision.
The formatting for display should be handled by PHP.
If storing in DB, you should of course store a currency code - which can be used when retrieving to tell PHP how to display it
Couldn't you use:
floatval($AnyVar)
In a case where you'd like to accept so many different formats it's a bit tricky to get it right.
Now we can just use a simple regex to get the decimal and full parts of the value:
/^([0-9,. ]+?)(?:[.,](\d{1,2})$|$)/
The regex will capture the full part of the number + a decimal part, separated with a , or a . and which has one or two numbers.
The capture group 1 will contain the full part, and group 2 the decimal part (if any).
To get your number, you just need to filter out all non-numeric characters from the full part, and join the filtered full and decimal parts together.
If you want to make it more foolproof, you probably should implement something on the client-side to guide the user to input the value in the correct format.

Add all lines multiplied by another line in another table

I hope I can explain this good enough. I have 3 tables. wo_parts, workorders and part2vendor. I am trying to get the cost price of all parts sold in a month. I have this script.
$scoreCostQuery = "SELECT SUM(part2vendor.cost*wo_parts.qty) as total_score
FROM part2vendor
INNER JOIN wo_parts
ON (wo_parts.pn=part2vendor.pn)
WHERE workorder=$workorder";
What I am trying to do is each part is in wo_parts (under partnumber [pn]). The cost of that item is in part2vendor (under part number[pn]). I need each part price in part2vendor to be multiplied by the quantity sold in wo_parts. The way all 3 tie up is workorders.ident=wo_parts.workorder and part2vendor.pn=wo_parts.pn. I hope someone can assist. The above script does not give me the same total as when added by calculator.
This is not an answer, just a comment.
Why don't you take the sum/multiply operation outside the SQL statement? I know, that seems stupid because it will increase the lines of code and the complexity of the script, but, imho, it is always a good thing to keep code and SQL statements as far away as possible.
The key cause I could see for something like this would be a type issue. For example, this could happen if you are using FLOATs instead of NUMERICs, you might get a slightly different answer. That is a mistake that is way too common, btw.
I would recommend double checking your schema to make sure you are using NUMERICs across the board here. NUMERIC is crazy-powerful on PostgreSQL, it performs very well, and it properly supports arbitrary precision operations. If you can't change the data type, cast your fields to numeric in your query.
FLOAT types (including DOUBLE) are fixed precision binary numbers, and they don't correspond exactly to base 10 numbers always. NUMERICs are stored internally as base 1000 (meaning 9 digits per 30 bits), and this is very efficient to convert to/from binary. The precision is also arbitrary, although it does have a maximum. However, for financial stuff, the maximum values or precision are not an issue with numeric data types. You should use them liberally.

Categories