imperium2335
imperium2335

Reputation: 24122

Using binary in MySQL and PHP for flags

Let's say I have the following flags that can be attached to a customer:

1 Hot
2 Urgent
4 Sensitive
8 Confidential

In my table I would store an active customer as an int of 6.

I figured doing things this way would save me a reference table and make querys faster.

How do I get PHP to interpret a 6 and for example light up a customer and active icon?

Upvotes: 1

Views: 288

Answers (1)

woz
woz

Reputation: 10994

Bitwise operators will do the trick:

$flag = 6; // value from the database
$customer = 2; // constant value
$active = 4; // constant value

if ($flag & $customer)
{
    print 'I am a customer.';
}

if($flag & $active)
{
    print 'I am active.';
}

I agree with @GordonLinoff though. Really consider if this is what you want because it's not easy to change later, and it could allow unexpected scenarios.

Upvotes: 1

Related Questions