TAGS :Viewed: 5 - Published at: a few seconds ago

[ Displaying the actual value of the field in textbox ]

Im making an insert record code in php then i need to make a auto code, or the user just can look at the prepared value of the textbox, Ill just use this code.

$ayos = mysql_fetch_array(mysql_query("select ib_code from item_brand order by ib_code desc limit 1"));
            $new_val = $ayos['ib_code'] + 1;

when you display it just use:

echo $ayos['ib_code'];

for example the output is 006. the thing i cant resolve was when i try to display value of *$new_val* in the textbox, for sure our expected result if the $ayos['ib_code'] = 006 then the $new_val is equal to 007, but the problem is it is only 7 not 007, when displaying inside the textbox.. thx

The screenshot of my problem thx guys!

Answer 1


if you want to display a number left-padded with zeros, consider using printf() (or one of its numerous relatives).

Tested Example:

    $a = '006';
    $b = $a + 1;
<input type="text" value="<?php printf("%03d", $b); ?>" />

Above code is tested.

sprintf() can do that:

echo sprintf('%03d', $ayos['ib_code']);

Or use str_pad() - but that's a little bit longer in code:

echo str_pad($ayos['ib_code'], 3, 0, STR_PAD_LEFT);

Response to Some User Comment

well if there are value like 0006 or 000006 then we can use above code is as below.

    $a = '000006';
    $b = $a + 1;
<input type="text" value="<?php printf("%0".strlen($a)."d", $b); ?>" />

what i am doing is passing length dynamically so if in future number size increase code will still work as expected.

Answer 2

Using the + operator forces PHP to interpret the variable as a number, which will truncate any leading zeroes. You'll have to do some interesting string manipulation most likely.

Answer 3

The 006 ins converted to number and after that it adds 1 to it, It becomes 7 , When it becomes number it truncates zeros from left side.Use below code, it will pad 0 to left.

echo str_pad($ayos['ib_code'], 3, "0", STR_PAD_LEFT); //becomes 007

Answer 4

Use $realnumber = intval($new_val);

echo $realnumber;

Answer 5

Assign $new_val variable like below:

//GET count of leading 0's into variable
$leading_zero_count = strspn($ayos['ib_code'], "0");    
$new_val = $ayos['ib_code']+1;
  * Pad the $new_val variable with 0's so that 
  * new length = total leading 0's + new length of $new_val
$new_val = str_pad ($new_val, $leading_zero_count+strlen($new_val),0, STR_PAD_LEFT);