Forum Moderators: coopster
I'm trying to populate the case values of a switch statement using a while() loop but I can't seem to get it to work. I've tried many different methods; currently my code looks like this:
[fixed]
function switch_name()
{
//.. load includes
$name_results = mysql_query("SELECT name FROM `table` WHERE column = 1");
$value_results = mysql_query("SELECT value FROM `table` WHERE column = 1");
$name_row = mysql_fetch_object($name_results);
if(mysql_num_rows($name_results) > 0 && mysql_num_rows($value_results) > 0)
{
while($value_row = mysql_fetch_object($value_results))
{
switch($_POST['$name_row->name']) {
case $value_row->value:
$x = $y;
break;
}
}
}
else
{
echo("");
}
}
[/fixed] In the page that I use this function, I check to see if $x is equal to $y, and if not then I return an error stating that an invalid value was submitted. With the above code, the invalid value error is always returned.
I think the problem is that this is creating many switch statements for every value, rather than creating one switch statement with multiple cases. Basically, I would like my function to create a switch statement where ever I call it and populate the cases of the switch statement - with the end result looking something like this:
[fixed]
switch($_POST['$name_row->name'])
{
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
$x = $y;
break;
}
[/fixed] Any suggestions? Thanks.
[fixed]
switch($_POST['$name_row->name'])
{
case '0':
case '220':
case '221':
case '222':
case '223':
case '224':
$x = $y;
break;
}
[/fixed] Is it possible, with your logic, to have $x = $y if $value_row->value == $_POST['$name_row->name'] and a value of 0 is delivered?
Thank you.
siMKin, thank you for your help; I really appreciate it. Your while loop will accomplish what a switch statement aims to accomplish, but it does not allow rogue values to pass. I use switch statements to ensure that the values I provide for input are the only values that make it to my action script. One of those values does not exist in my database, and that is the value of 0. I use 0 to allow users to select a blank option; '<option value="0"> </option>'. This:
[fixed]
while($value_row = mysql_fetch_object($value_results))
{
if ($value_row->value == $_POST['$name_row->name'])
{
$x = $y;
}
}
[/fixed] Is equivalent to this:
[fixed]
switch($_POST['example'])
{
case '220':
case '221':
case '222':
case '223':
case '224':
$x = $y;
break;
}
[/fixed] But not this:
[fixed]
switch($_POST['example'])
{
case '0':
case '220':
case '221':
case '222':
case '223':
case '224':
$x = $y;
break;
}
[/fixed] And that is what I was getting at. Actually, it just hit me that I could simply add in the value of 0 before the while loop initiates, and that would do the same thing as a switch with case '0'. Thanks again.