Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting PHP float/decimal values into MySQL

It's a pretty simple question to be honest. I've been looking for a while now on Google for a solution but nothing seems to work. I have the following field in my database:

decimal(2,1)

I have two variables in PHP (which come from values inserted into a form via POST) I want to add together and then insert into this field.

$sql2 = $link->prepare("INSERT INTO league_stats (match_id, rating)
VALUES (?, ?)");
$sql->bind_param("ii", $match_id, $rating);

$match_id = $_SESSION["match_id"];
$rtg1 = $_POST[$rating_1"];
$rtg2 = $_POST[$rating_2"] / 10;
$rating = $rtg1 + $rtg2;

For example, rtg1 would be 7 and rtg2 would be 3 divided by 10 so it comes out as 0.3. I then add these two numbers together to make 7.3. When I go to insert it into the database, it always displays the second digit as 0. So instead of 7.3 it would come out as 7.0. I've tried many different methods but I always get the exact same result.

I even assigned $rating to a raw value just to test if there was something wrong with my variables:

$rating = 7.5

Still comes out as 7.0.

Could somebody please provide an example of how to correctly insert a float type PHP variable into MySQL? And also maybe explain how to correctly add two float values together? Thanks!

like image 618
samer.j92 Avatar asked Jan 23 '26 11:01

samer.j92


1 Answers

You are telling php to cast $match_id and $rating to integer. You should use:

$sql->bind_param("id", $match_id, $rating);

instead of

$sql->bind_param("ii", ...
like image 146
l-x Avatar answered Jan 25 '26 00:01

l-x