简体   繁体   中英

php / mysql, need advice on method to store this data

Basically on my website there are checkboxes for each day of the week. If a user checks them, those are the days to be saved (in a field) in their user account.

How would I go about saving these dates? For example, if someone checks Saturday and Wednesday, another saves Monday and Tuesday, what's a good pattern to keep this info?

Someone suggested saving it as a bit string like 0001001 the 1's representing the days of the week check marked, out of the 7 bits representing each day. Any ideas?

The table would look like this:

user_id | days
10      | 0010010 (Wednesday and Saturday, week starts on Monday)

The only issue with is how would I output this info from php?

(I'm trying to do this in the most optimal way both on the mysql and php side)

The suggestion to use a bit field type in MySQL with a length of seven sounds fair to keep storage requirements low ( BIT(7) ).

The only issue with is how would I output this info from php?

The first step would be to define a mapping of each bit to a weekday-name:

$days = array(
   'Monday',
   'Tuesday',
   ...
   'Sunday'
);

Then you first need to select the binary value from the database, eg as a decimal (integer) value:

SELECT days+0 FROM table;

In PHP you can convert this to a fixed-width binary number string using decbin and substr :

$binary = substr('000000'.decbin($integer), -7);

or probably more convenient sprintf :

$binary = sprintf('%07b', $integer);

As each of those characters is either 0 or 1 you can iterate over them and create an array for all set days:

$array = array();
foreach (range(0, 7) as $day)
{
    if (! $set = (int) $binary[$day])
        continue;

    $array[] = $days[$day];
}

The resulting $array contains now all weekday names that the user checked. You can then output them:

$output = '(none)';
if (1 === $count = count($array)
{
    $output = $array[0]; # one day
}
elseif ($count)
{
   $last = array_pop($array); # last day
   $output = implode(', ', $array) . ' and ' . $last;
}

That was the output of the database value. Hope this is helpful.

I would suggest a table like this:

   id user_id day
   1     1     1
   2     1     4
   3     2     1
   4     3     7

You can store the days in a serialized array, and that way, get it back easily when you want it.

$days = array('wednesday','saturday');
$store = serialize($days);

and then store $store for that user_id

I think it would be easier to store like this:

user_id | sun | mon | tues | wed |...
     01 |  1  |  0  |  0   |  1  |

And leave the day columns as tinyint(1)'s. That way, in PHP, you could just go like this:

if($row['sun'] == 1)
    Do sunday stuff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM