MySQl leading zeros get stored but wrong display - php

I am trying many typed of fields in MySQL to store numbers only, tried with INT, BIGINT with leading zeros, CHAR and VARCHAR to store INVOICE NUMBERS
I need the invoice numbers to be start with 0000000001, I stored it manually in PHPmyadmin
Now I want to display it and I dont get the leading zeros ....
Here is the database
field "folio" CHAR 15 stored I have manually did 0000000001 it displays fine on phpmyadmin
but here is the problem
<?php $maxprod=mysqli_query($datacenter,
"SELECT * FROM ventas
WHERE documento = 'boleta'
ORDER BY id DESC LIMIT 1");
while($lastcode=mysqli_fetch_assoc($maxprod)){?>
<input type="text" value="<?php echo $lastcode['folio']+1?>">
<?php }?>
the result of the query is 1 just 1 it does not display all other zeros
Any idea why?

PHP automatically converts string into number if you are performing any numerical operation on it. But you can keep the order number in integer form and pad it with zeroes when necessary:
str_pad($lastcode['folio']+1, 15, "0", STR_PAD_LEFT);

echo $lastcode['folio'] should show you a result with the leading zeroes, but not $lastcode['folio']+1.
As soon as you do that +1, the result is no longer a string. The $lastcode['folio'] variable is converted to a number in order to do the arithmetic operation on it.
The leading zeroes are just formatting and don't need to be stored with the number. If you need an autoincrementing number, just use an autoincrement integer in MySQL, and format the number with leading zeroes when you print it out.

This will retrieve the number as a string to display it as text.
Later you can manipulate it on your coding environment.
SELECT CAST(document_number AS CHAR) FROM ...

Related

PHP: strings automatically converted to float and gives negative numbers

I have a PHP code that will compute the balance of the quantity but it gives me a negative value as a balance quantity as shown in the image below.
I tried to check the quantities if what's causing the problem and try to var_dump the quantity. after checking using var_dump, it shows that the data type of my quantity is string while my balance quantity is float.
so far, I have my code below:
$query_po_quantity = mysqli_query($new_conn, "SELECT quantity, po_number FROM purchase_order WHERE supplier_name = '$supplier_name' AND category_name = '$category_name' AND activity = '$activity' AND description = '$description'");
$row = mysqli_fetch_assoc($query_po_quantity);
$po_quantity = $row['quantity'];
$po_number = $row['po_number'];
$query_rr_quantity = mysqli_query($new_conn, "SELECT SUM(total_received) AS quantity FROM receiving_reports WHERE po_number = '$po_number' AND category_name = '$category_name' AND activity = '$activity' AND description = '$description'");
$row = mysqli_fetch_assoc($query_rr_quantity);
$rr_quantity = $row['quantity'];
$balance = $po_quantity - $rr_quantity;
$supplier_name = preg_replace('/\\\\/', '', $supplier_name);
echo $po_quantity.' - '.$rr_quantity.' = '.$balance.'<br />';
This is the output:
how can I get the actual balance?
The reason you're getting an incorrect result when calculating 0.42 - 0.420000000000000000004 is due to errors with floating point precision. This is due to the way floating point numbers are stored, and both MySQL and PHP are susceptible to floating point errors if done incorrectly, but they also both have ways to prevent them when you do need highly precise calculations. With floating point types only the approximate value is stored and attempts to treat them as exact values in comparisons may lead to problems.
For PHP, this means you need to use either the arbitrary precision math functions or gmp functions. For MySQL, you need to be storing the numbers using the DECIMAL format with the desired precision you require.
First thing's first, you need to change the data type of your column in MySQL to DECIMAL, not a string. Strings are inappropriate to store numbers. Even if you were using a FLOAT or DOUBLE to store your values
your code may have actually worked, because these values likely would have been rounded.
Next, seeing as the value 0.420000000000000000004 came from a string stored in your database, I'm assuming the error stems from whatever calculations you did using PHP beforehand when you were calculating the value to be inserted. You will need to update this code to use precise math.
Use number_format:
$rr_quantity = number_format($row['quantity'], 2);
Float variable range 1.7E-308 and 1.7E+308 so it's give 15 digits of accuracy. Use number format

How can I format a number with leading zeros and thousands commas?

I have an int field in a MySQL database that is progressively going up every time a user of the database performs a specific action so it's going up in increments of 1.
When displaying this on a php page, I want it to display this value as 0,000,001 rather than it's raw data of just 1.
How do I format the number to display like this? I've never had to do it before, so I'm bewildered.
Something like this should work:
SELECT INSERT(INSERT(LPAD([value], 7, '0'), 5, 0, ','), 2, 0, ',')
FROM ....
LPAD returns a string of length 7, with leading 0's. If [value] is longer than 7 it will be truncated (from the right); so '12345678' becomes '1234567'.
The two INSERT calls insert the commas.
Edit: Changed the 1's to 0's; apparently they effectively made it a "replace" rather than an "insert".
I'd suggest doing this in code though, instead of a query, if you can.
If you would rather do it in the php, something like:
$pretty = substr(number_format(10000000 + $counter), 1);
this will work as long as counter never exceeds 9,999,999.

Value being inserted as 2147483647 into database

All phone numbers I am trying to enter into my database are being inserted as 2147483647.
The database field is an integer(11).
Before the phone number is inserted, it goes through the following code in order to remove all spaces, dashes, and brackets:
if (!empty($hphone)) $phone = $hphone;
else if (!empty($HomePhone)) $phone = $HomePhone;
else if (!empty($Phone1)) $phone = $Phone1;
$phone = preg_replace("/[^0-9]/", "", $phone);
Why is it inserting the phone number as 2147483647 every time, no matter what the phone number is?
If you can, convert the phone number to a VARCHAR field, don't store it as a signed (or unsigned) numeric value (int, bigint, double, etc...).
In this case, the limit for signed INT in MySQL of 2147483647 is what is causing your issue. Anything larger inserted into this field will be capped at that maximum value.
For example the phone number 555-555-5555 if bigger than that limit (5555555555 >2147483647), as such storing it would result in the max value 2147483647.
I also recommend not storing it as a BIG INT or any other numeric type. How will you handle extension or special encoded characters like:
+02 112020 10020
1-333-232-9393 x203
BTW: don't know if the first is real non-US number format, but you get the idea
Also, phone numbers with relevant leading 0's would be have some of it lost no mater how large the number:
021-392-9293
Would be the number 213929293
if you want to store it as a number use bigint because int has it's max value equal to 2147483647.
So whatever number you try to store that is higher than 2147483647 will be stored as 2147483647.
Here is some reference for mysql types:
http://dev.mysql.com/doc/refman/5.0/en/integer-types.html
I am also facing this type of problem and I have solved that problem after
Updating datatype From 'INT' TO 'BIGINT'.
#php #mysql #database #sql

Hiding the decimal if .0 and showing zero if an integer

I have two, hopefully basic number questions.
First, I am using the decimal data type on MySQL to show data like speed or height set to one decimal place like this decimal(4,1) My problem is that for numbers with no dp it is still showing .0 - What I get is '309.0' but what I want is '309'. What do I need to change to hide the '.0'?
Second I have an integer data type showing fixed numbers. Many of the numbers are 0 zero but these are getting treated as null and not displaying. How do I force the 0's to display? (I can't make table changes for this because other columns do have zero's that are null values. It is only this one column that needs zeros to display).
For both of these problems PHP is being used to display the results.
EDIT: code I'm using to display results. the top one needs to not show .0 the bottom one needs to show a zero.
Length:</b> %sft' . PHP_EOL, $row2['length'])
Inversions:</b> %s' . PHP_EOL, $row2['inversions'])
I believe a sneaky trick is if you add 0 to the end of your number, it removes the .0000 etc.
example:
$number = 150.00
$number = $number + 0; //should echo 150
$other_number = 150.500;
$other_number += 0; //should echo 150.5
As for the other, you can simply concatenate the zeros since no calculations seem to be needed
To check for the trailing zero, you could use the following to make sure that the float and integer values are the same:
$num = (floatval($num)==intval($num)) ? intval($num) : floatval($num);
and then for the null value, you could use coalesce(yourColumn, 0) as yourColumn to either get your column value if not null or return 0 as the value..

float not working in mysql database

i am using $_GET['var'] to get a variable then compare it with a variable in my database. the variable is 1.1 the var is set to "float" on the database so i know it can handle decimals but when i compare them with the code below i get nothing.
include 'connect.php';
$sql=mysql_query("SELECT * FROM table WHERE stuff='$stuff'");
while ($row=mysql_fetch_assoc($sql)) {
$start=$row['start'];
}
echo $start; //nothing happens
From what I know float type isn't precise. It doesn't show you that actual value so 1.1 that you saved may not be the actual value stored. Trying setting your field as decimal and give it a length of say, 10,1 where 10 is the maximum number of digits (the precision) and 1 is the number of digits to the right of the decimal point (the scale). It should work doing query like stuff='1.1' or stuff=1.1.
WHERE stuff = '$stuff' is a String comparison.
Compare number like so
WHERE stuff = $stuff
Don't use float( even if you insert 1.1 into the table, the actual value for float type is not 1.1, but something like 1.100000023841858) . Change it to double in database (or decimal)
You might not be seeing any output because your echo is outside the loop.
The scope of your variable $start would be confined to the loop.
Change the stuff field to DOUBLE type.
Then,
SELECT * FROM table WHERE stuff=$stuff
this should be the sql query

Categories