简体   繁体   中英

<select SELECTED> IF Statement within a Loop

Hope this question makes sense! I have an edit page which has a

<option><select> 

part The

<select>

options themselves are from a database, so they are in a loop to have values as IDs and friendly name in the display bit. See below.

// Start loop to display products
                    $i=0;
                    while ($i < $num2) {

                        $catid=mysql_result($result2,$i,"id");
                        $catname=mysql_result($result2,$i,"category");



                //Write each product
                echo '<option value="';
                echo "$catid";
                echo '"';
                if ('$catid'=='$f_cat_id')
                {
                    echo ' selected ';
                }
                echo $f_cat_id;
                echo '>';
                echo "$catname";
                echo '</option>';


                // Repeat loop until finished
                        $i++;
                    } 

You can see that as this is an EDIT page i have the value that was previously selected in a variable called $f_cat_id. Now i want to default it to Select IF $f_cat_id matches the value in the loop.

It seems however that my variable which is set like this...

$f_cat_id=$row['product_category_id'];

Doesn't seem to be available to use in an IF statement whilst in the loop?

Sure this is an easy question! look forward to your help! Many thanks in advance.

You're comparing two strings:

'$catid'=='$f_cat_id'

Single quotes don't interpolate variables (you should use double quotes for variable interpolation ).

Anyway you don't need interpolation at all, since you can simply compare the two variables:

if ($catid == $f_cat_id)
{
    echo ' selected ';
}
if ('$catid'=='$f_cat_id')

That's the cause of the issue. PHP variables aren't interpolated when they're in single quotes. The if condition will always evaluate to FALSE and the code inside the if block won't get executed.

To prove it, consider the following expression:

$catid = 1;
$f_cat_id = 1;
var_dump('$catid' == '$f_cat_id');

The output will be:

bool(false)

So, change your code to:

if ($catid == $f_cat_id) {
    # code ...
}

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