0

What i want to do is when semester is equals to "1" it will print "st Semester S.Y" else if semester is equals to "2" it will print "nd Semester S.Y". But the problem is i get an error of Parse error: syntax error, unexpected 'if' (T_IF). Can someone help me about this?

here's my code.

if(isset($_POST['loadsem'])){
      $stud = $_POST['stud'];
        $output = '';  
    $sql = "SELECT DISTINCT sch_year,semester FROM grades WHERE stud_no ='$stud'";
    $result = mysqli_query($con,$sql);
    $output .= '
                  <div class="table-responsive">
                    <table class="table table-bordered">
                      <tr>
                    <th>Semesters Attended</th>
                      </tr>';
      while($row = mysqli_fetch_array($result))
      {
        $sem = $row['semester'];
        $year = $row['sch_year'];
        $output .= '<tr>
                    <td><a href="">'.
                     if($sem == "1"){
                      $row['semester']. "st Semester S.Y" .$row['sch_year']
                    }
                    else{
                      $row['semester']. "nd Semester S.Y" .$row['sch_year']
                    }
                    .'</a></td>
                    </tr>
          ';
      }
          $output .= '</table>
            </div>';
   echo $output;


}
nethken
  • 1,072
  • 7
  • 24
  • 40
  • You cannot concatenate conditional operator into a string. instead break your variable – Thamilhan Dec 20 '16 at 04:54
  • You can't do a `if`/`else` block in the middle of a variable concatenate - `$output .= '...'. if(){ } else{ } .'... ';` – Sean Dec 20 '16 at 04:55

3 Answers3

3

You cannot concatenate an if statement.

$output .= '<tr>
    <td><a href="">';
if($sem == "1") {
  $output .= $row['semester']. "st Semester S.Y" .$row['sch_year'];
} else {
  $output .= $row['semester']. "nd Semester S.Y" .$row['sch_year'];
}
$output .='</a></td>
    </tr>';

If you still wanna concatenate, you need to use ternary operator: (condition) ? true : false.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
2

You cant do a function in if statesments so allways when u canna do php code end your print or varable. and add the new code

exemple 1:

echo 'hello'; 
if($world == true){
 echo 'foo';
}else{
 echo 'bar;'
}

exemple 2:

$i = 'hello'; 
if($world == true){
$i .='foo';
}else{
$i .='bar;'
}

in both exemple i end.

.= means add so you know

1

you cannot use if else like that, but you can use ?: in (). Here is a simple demo

change you if else

if($sem == "1"){
  $row['semester']. "st Semester S.Y" .$row['sch_year']
}
else{
  $row['semester']. "nd Semester S.Y" .$row['sch_year']
}

to: (?:)

($sem == "1" ? $row['semester']. "st Semester S.Y" .$row['sch_year'] : $row['semester']. "nd Semester S.Y" .$row['sch_year'])
LF00
  • 27,015
  • 29
  • 156
  • 295