Having <? within an echo statement

Discussion in 'PHP' started by srandal1, Oct 7, 2008.

  1. #1
    Hello,

    Am fairly new to PHP and am stuck right now. I have a user update profile form with a select box for the user's state. I call a function to grab the states and build them into options for a select box.

    When not dealing with many entries, in the past I have not used the function and used something along the lines of:

    <option value="0" <?php if ($_SESSSION['service']['fax'] == "0") echo ' selected="selected"'; ?> >0</option>
    Code (markup):
    However, as I am not that good yet at escaping with PHP I am having a bear of a time implementing it within the function. Here is the function and you can see what I am trying to do:

    function buildStates() {
    
           $sql = "SELECT * from states;";
    	$result = dbQuery($sql) or die('Cannot get Parts. ' . mysql_error());
    
    
    	while($row = mysql_fetch_assoc($result)) {
    		$state = $row['state_abbr'];
    		echo "<option value=\"$state\" <?php if ({$_SESSION[user][state]} = $state) echo ' selected="selected"'; ?> >$state</option>\n";
    	
    	}
    }
    Code (markup):
    I have tried every escape combination that would make sense to me, but I always get the unexpected T_STRING error.

    Thanks for any suggestions...
     
    srandal1, Oct 7, 2008 IP
  2. caffeinefree

    caffeinefree Guest

    Messages:
    43
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Try this:

    <?php
    $state = $row['state_abbr'];
    echo "<option value=\"$state\" "; if ($_SESSION[user][state]==$state){echo "selected=\"selected\">$state</option>";}
    ?>
     
    caffeinefree, Oct 7, 2008 IP
  3. caffeinefree

    caffeinefree Guest

    Messages:
    43
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Oh.. unless user and state are constants, you will need to change the way you're indexing $_Session.
    I assume they are variables so.. should be
    $_Session[$user][$state]
     
    caffeinefree, Oct 7, 2008 IP
  4. srandal1

    srandal1 Peon

    Messages:
    6
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Thanks caffeinefree, worked like a champ. Dah!! Feel like a moron. My final use was this:

    echo "<option value=\"$state\" "; if ($_SESSION['user']['state']==$state){echo "selected=\"selected\"";}echo ">$state</option>";
    Code (markup):
     
    srandal1, Oct 7, 2008 IP
  5. cn45896

    cn45896 Guest

    Messages:
    140
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Nice - seomtimes it's too easy to overlook
     
    cn45896, Oct 8, 2008 IP