Jump to content

Help with using PHP variable to look for field name in mysql table


jcjst21

Recommended Posts

I am using this function to get the day of the week and placing it into a variable called $today

 

$today=date("l");

 

I have a mysql table that has 7 fields one for each day of the week, and in that field if a checkbox on the form selects that day, a "1" is placed in the table and "0" of it is not

 

I want to easily look for that field using the $today variable

 

Can I do this in my mysql statement when i use a while loop?

 

$getSchedule=mysql_query("SELECT * FROM schedule");

$schedule=mysql_fetch_array($getSchedule);

 

while($schedule[$today]=="1")

{

  /* where $today will place the value for instance $today will place "Sunday" for $schedule[sunday] */

}

 

Will this work or do I need to it another way?

 

Thanks,

jcjst21

Ok.  So I can't use the php variable "today" to place the field name in the $schedule['today'] field?

 

I have seven fields for Sunday through Saturday, by using the $today variable it will place what day of the week it is so the mysql will know what field in the table to look at...

 

so I don't have to have a bunch of if statements to look at each field for each day of the week.

 

 

Depends on what you want to do with the rows that have the column matching $today as 1.  What you posted is perfectly valid:

 

$today = date("l");
$getSchedule = mysql_query("SELECT * FROM schedule");

while($schedule = mysql_fetch_array($getSchedule)) {
   if($schedule[$today] == 1) {
      // do something
   }
}

But if you just want rows for today you could just do:

 

$getSchedule = mysql_query("SELECT * FROM schedule WHERE $today = 1");

ok so I can use the php variable in place of a field name in a mysql statement?

 

That will work?

If it will that's great, that's what i need to avoid tons of if statements.

Yes, but you might be better off changing the database to have a separate table with the days for each event and then join it when you query:

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.