Nuv Posted March 15, 2011 Share Posted March 15, 2011 Hi, I made a code to add 0 infront of any zipcode with 4 digits. I think this can be done in a better way.Maybe using only sql by LEN('string') or DATALENGTH('string'). Can someone please show me how ? Is there any better way ? <?php $mysql_hostname = "localhost"; $mysql_user = "root"; $mysql_password = ""; $mysql_database = "flourists"; $bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong"); mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong"); $result = mysql_query("SELECT * FROM bakers"); while($row = mysql_fetch_array($result)) { if((strlen($row['pincode'])) == 4 ) { echo $row['pincode'] ; echo "<br />"; $addzero = "0"; $newpincode = $addzero.$row['pincode']; echo $newpincode; echo "<br />"; echo "<br />"; // will add UPDATE sql query to update $newpincode } } ?> Quote Link to comment https://forums.phpfreaks.com/topic/230678-how-can-i-do-this-in-a-better-way/ Share on other sites More sharing options...
spaceman12 Posted March 15, 2011 Share Posted March 15, 2011 Do it this ways which is alot cleaner. $pincode=$row['pincode']; If(strlen($pincode)==4) { $pincode='0'.$pincode; } Quote Link to comment https://forums.phpfreaks.com/topic/230678-how-can-i-do-this-in-a-better-way/#findComment-1187676 Share on other sites More sharing options...
coolcam262 Posted March 15, 2011 Share Posted March 15, 2011 You could even just do: If(strlen($row['pincode'])==4) $pincode='0'.$pincode; Quote Link to comment https://forums.phpfreaks.com/topic/230678-how-can-i-do-this-in-a-better-way/#findComment-1187692 Share on other sites More sharing options...
cyberRobot Posted March 15, 2011 Share Posted March 15, 2011 Or you could use sprintf() http://php.net/manual/en/function.sprintf.php $row['pincode'] = sprintf("%05d", $row['pincode']); Quote Link to comment https://forums.phpfreaks.com/topic/230678-how-can-i-do-this-in-a-better-way/#findComment-1187728 Share on other sites More sharing options...
sasa Posted March 16, 2011 Share Posted March 16, 2011 you can do it in MYSQL with LPAD() function http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_lpad Quote Link to comment https://forums.phpfreaks.com/topic/230678-how-can-i-do-this-in-a-better-way/#findComment-1188048 Share on other sites More sharing options...
Nuv Posted March 16, 2011 Author Share Posted March 16, 2011 you can do it in MYSQL with LPAD() function http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_lpad Ah thats what i was looking for . Thankyou Quote Link to comment https://forums.phpfreaks.com/topic/230678-how-can-i-do-this-in-a-better-way/#findComment-1188059 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.