php echo within an echo for a checkbox

14,350

Solution 1

echo"<input type='checkbox' name='PLJan' {if (isset($_POST['PLJan'])) print 'value='checked''} $row->PLJan /> January ";

should be

echo"<input type='checkbox' name='PLJan'"; 
if (isset($_POST['PLJan'])) { echo " value='checked'"; } 
echo $row->PLJan . "/> January ";

Solution 2

Your notation is all off ... simplest solution is to break it apart to muliple echo statements.

echo "<input type='checkbox' name='PLJan' ";
if (isset($_POST['PLJan'])){  
        echo  "checked='checked'";
} 
echo "value='".$row->PLJan."'/> January ";

With that you can simplify it using a ternary if

echo "<input type='checkbox' name='PLJan' ";
echo (isset($_POST['PLJan'])?"checked='checked'":"");
echo "value='".$row->PLJan."'/> January ";

And if you want to compress it down to a single line you can concatenate the echos together

echo "<input type='checkbox' name='PLJan' ".(isset($_POST['PLJan'])?"checked='checked'":"")." value='".$row->PLJan."'/> January ";
Share:
14,350
SyrupandSass
Author by

SyrupandSass

I build websites.

Updated on June 25, 2022

Comments

  • SyrupandSass
    SyrupandSass almost 2 years

    I'm trying to use checkboxes to display and update records in a MySQL database. I want to change the value of the checkbox based on whether it's checked or unchecked. But I'm getting this error:

    Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

    Here's the line of code that's throwing the error:

    echo"<input type='checkbox' name='PLJan' {if (isset($_POST['PLJan'])) print 'value='checked''} $row->PLJan /> January ";

    Is there a better way for me to do this so that saving it will update the database with 'checked' if the box is checked, and a blank if the box is unchecked?

    Thanks in advance for the halps.