3

I have a table like this:

// numbers
+---------+------------+
|    id   |    numb    |
+---------+------------+
| int(11) |   bit(10)  |
+---------+------------+
| 1       | 0000000001 |
| 2       | 0000000101 |
| 3       | 0000000000 |
| 4       | 0000001011 |
+---------+------------+

When I fetch numb column, the result will be like this:

// Query
mysql> SELECT numb FROM numbers WHERE id = 2

// Fetching by PHP (pdo)
$result = $stm->fetch();
$numb   = $result['numb'];
echo $numb;
//=> 5

As you see, the final result is 5. While I want to get that exact value as a string, like this 0000000101. How can I do that?

3
  • Use decbin() Commented May 9, 2016 at 4:33
  • @Thamizhan By using that function, the result isn't always 10 digits. It will be depends on the number. 12 => 1100, 26 => 11010. While I want to get a binary number based 10. Commented May 9, 2016 at 4:36
  • Just pad zeros to it! Look at the answer section Commented May 9, 2016 at 4:38

2 Answers 2

3

You can use decbin() function and sprintf for pre-pending zeros

<?php

$numb = 5;
echo sprintf("%010d",decbin($numb));

Output:

0000000101

From your comments:

12 - 0000001100
26 - 0000011010

Update1:

You can assign to $numb variable like this:

$numb = sprintf("%010d",decbin($result['numb']));
Sign up to request clarification or add additional context in comments.

3 Comments

Thx .. That's correct. +1 ..! Also as a note I want to know, can I do that in the query? I mean by using something like concat() and making numb's value as string.
@Shafizadeh So only I added sprintf. You can assign the value similar to echo. See the updated answer
Look, forget using sprintf() and decbin() functions. I'm trying to do that by pure-sql (not php-side). Is that possible? All I want to know is getting the value of a numerical column as string. Something like this (doesn't work): . . . CONVERT(VARCHAR(10),numb) active . . .
3

This is completely using SQL as you requested:

Using CONV() and LPAD():

LPAD(CONV(id,10,2),10,0)

Here is SQLFiddle for you

4 Comments

Wait .. your fiddle isn't correct, where is numb column? You have created it as an alias. That's a real column in my table. In other word, numb column isn't related to id column at all.
Then add your schema or sample data here so I might help you out
@Shafizadeh Checkout the updated link: SQLfiddle
Better ... But in your fiddle numb is integer. May you please change it to BIT(10)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.