简体   繁体   中英

PHP Mysqli query comparing string-type number field to an integer

I have a database where one of the fields is for bathrooms and users usually input 1 or 3 or sometimes 1.1 which means 1 full bathroom and 1 half bathroom so I couldn't store this field as number, integer or double, or decimal. I had to store them as text.

My question is, how can I do this in a query if I wanted to pull only those records who's bathrooms is greater than 3 or something? I am looking for something like:

SELECT * FROM agentdb WHERE converttointeger(bathrooms) => 3

Obviously converttointeger is not valid but is there a way to achieve this? I tried searching and Googling but I keep getting the wrong results or wrong topic.

Don't use text converted to integers. Store the values as numbers with a decimal portions such as decimal . Then you can use the > comparison with no need for casting.

I would use DECIMAL(2,1) , meaning 2 digits, including 1 decimal digit. "1.1" would be saved as 1.1 , not 1.10

Alternative: You could also have two table fields: full_baths and half_baths , each of type tinyint or smallint . When your user enters "1.1" just split it before storing

$baths = $_POST['bathrooms'];// eg: "2.1"
$baths_arr = explode(".",$baths); // eg: [2,1]

$full = $half = 0; //full baths, half baths
if(!empty($baths_arr)):
    $full = (int)$baths_arr[0]; //we explicitly convert to integer
    $half = empty($baths_arr[1])? 0: (int)$baths_arr[1];
endif;

Then you can save $full and $half in their respective columns

This should work: SELECT * FROM agentdb WHERE CAST(bathrooms AS SIGNED) >= 3

I got the answer from here: Cast from VARCHAR to INT - MySQL

将它们存储为浮点数,以便您可以保留小数,但将其保留为数字。

'bathrooms' data = { 1, 3, {3 < int}}

You need only 3 or 3 over integer. Conversely Think! You don't need '1' data. So...

SELECT * FROM agentdb WHERE bathrooms <> '1'

And, Casted columnn is not working index.

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