I have data stored in SQL as an integer between 0 and 63, IE six bits.
I am trying to execute (or not) 6 simple statements based on respective bit values.
I want to know which method is the most efficient, or possibly if I’m making my life far harder than it has to be (which I suspect is true).
Method 1:
Loop working from smallest to largest. Divide the integer by 2, if not an integer then subtract .5 and the first bit is true. Repeat until the value is zero.
Method 2:
Convert to binary, pad with leading zeroes, then reading each character of the output string. (lots of functions and type conversions.)
$bit = str_pad(decbin($row['utilities']),6,"0", STR_PAD_LEFT)
Method 3:
Loop working from largest to smallest. If the integer is greater than 32, then subtract 32 and the last bit is true. Divide test digit by 2 and repeat until testing for 0.5.
This is the code I’m actually working with. (Where $row[‘utilities’] is output from SQL and contains a number between 0 and 63 inclusive) The form element which creates the data for storage in the SQL database is identical except for the php.
$bit = ???
<select name="ut[]" multiple="multiple" class="postSelect">
<option <?php if ($row['utilities']==0) {echo "selected='selected'";}?> value="0">None</option>
<option <?php if (bit['0']) {echo "selected='selected'";}?> value="1">Electricity</option>
<option <?php if (bit['1']) {echo "selected='selected'";}?> value="2">Water</option>
<option <?php if (bit['2']) {echo "selected='selected'";}?> value="4">Heat</option>
<option <?php if (bit['3']) {echo "selected='selected'";}?> value="8">Phone</option>
<option <?php if (bit['4']) {echo "selected='selected'";}?> value="16">Internet</option>
<option <?php if (bit['5']) {echo "selected='selected'";}?> value="32">Laundry</option>
</select>
My advice:
For this use a bitwise operator instead of
decbinand such. This makes it not only easier, but cleans up the code alot.Syntax:
Here’s a wonderful example taken from the php manual:
You can do this in MySQL, too, but from my experience this usually makes your code longer and not as good as readable.