Waye J
Waye J

Reputation: 21

Remove leading zeros in php mysql

I have numbers in a table in a database which I want to echo without a the leading zeroes. When I remove the trim, the numbers are able to echo but with the trim is not echoing, any suggestions? Here is the code:

<?php
     $msg = "SELECT TRIM(LEADING '0' FROM Phone) FROM members";
     $msgtxt = $pdo->query($msg);
     $msgtxt->setFetchMode(PDO::FETCH_ASSOC);
     while($ymsg=$msgtxt->fetch()){
        echo $ymsg['Phone']. ",";
     }
?>

But the code is not working!!!

Upvotes: 1

Views: 1459

Answers (2)

kchason
kchason

Reputation: 2885

If you wanted to do it in PHP, you can use ltrim (docs).

<?php
$phone = '0009398349838';
// Remove leading 0s
$phone = ltrim($phone, '0');
// Print new number
echo $phone;

So in your example:

<?php
...
while($ymsg=$msgtxt->fetch()){
    echo ltrim($ymsg['Phone'],'0'). ",";
}
...

Upvotes: 2

Lukasz Szozda
Lukasz Szozda

Reputation: 175596

Use alias:

SELECT TRIM(LEADING '0' FROM Phone) AS Phone FROM members

to get the same column name. Then echo $ymsg['Phone']. ","; will work.

Upvotes: 4

Related Questions