Jump to content

How does this if statement within some dropdown code work?


spenceddd

Recommended Posts

Hi,

 

Being an absolute novice I am struggling to work out how this if statement work (within some code for a drop down menu):

 

<option value="<?php echo $row_PortfolioItems['id']?>"<?php if (!(strcmp($row_PortfolioItems['id'], $_POST['name']))) {echo "SELECTED";} ?>><?php echo $row_PortfolioItems['name']?></option>

 

What I don't understand is why the string compare function is comparing two things that will never match, $row_PortfolioItems['id'] and $_POST['name'] as one is a number and one is a string...also I don't really get how the whole line works in terms of the html that it generates. Would be grateful if someone could break it down for me.

 

Thanks for any help.

 

Spencer

You are right, unless you were to pass $row_portfolioItems['id'] through chr, strcmp won't ever return '0' (meaning no row would ever have "SELECTED"). You'd first have to use a SELECT-query to get all the values of `name`, run-through those results in a while()-loop, and while in that loop IF the database-value matches the form-value echo '<option ... SELECTED>...</option> ELSE echo <option> ... </option>

Ah yes well I didn't show all the code as I thought it may raise more questions but that code does seem to work, or at least the drop dowm functions correctly. I'm just trying to understand it so I can apply it to other drop downs in my form.

 

Here is the rest of the code for the drop down:

 

<select name="name" onChange="chkFrm(this)">
    <option value="Choose" <?php if (!(strcmp("Choose", $_POST['name']))) {echo "SELECTED";} ?>>Choose Portfolio Items</option>
     <?php do { ?>
    <option value="<?php echo $row_PortfolioItems['id']?>"<?php if (!(strcmp($row_PortfolioItems['id'], $_POST['name']))) {echo "SELECTED";} ?>><?php echo $row_PortfolioItems['name']?></option>
    <?php 
} while ($row_PortfolioItems = mysql_fetch_assoc($PortfolioItems)); 
  $rows = mysql_num_rows($PortfolioItems); 
  if($rows > 0) { 
      mysql_data_seek($PortfolioItems, 0); 
      $row_PortfolioItems = mysql_fetch_assoc($PortfolioItems); 
  
  } 
?>
  </select>

 

Again any help on explaining this would help me a lot.

 

Spence

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.