如何使用php在链接中使用else类

时间:2018-03-24 10:30:17

标签: javascript php html css

如何在使用PHP的链接中使用else

我想在课堂上添加条件我该怎么做才能帮我解决这个问题

感谢

if ($user == 'brother' ) {

echo "<img src=\"images/bandmember.jpg\" class=\"right\" >";
} else {
    echo "<img src=\"images/gismember.jpg\" class=\"left\" >";
}

它会显示这样的结果

<img src="images/bandmember.jpg" class="right">
<img src="images/gismember.jpg" class="right">

我希望结果像这样

<img src="images/bandmember.jpg" class="right">
<img src="images/gismember.jpg" class="left">

这里是完整的代码

<?php

include 'db.php';


   $sql = 'SELECT * FROM users';

   if($result = mysqli_query($con, $sql)) {
      if(mysqli_num_rows($result) > 0) {


         while($row = mysqli_fetch_array($result)){
            echo "<div class=\"container\">";


              if ($row['username'] == 'brother' ) {

    echo "<img src=\"images/" . $row['photo'] . "\" class=\"right\" >";
    } else {
        echo "<img src=\"images/" . $row['photo'] . "\" class=\"left\" >";
    }

        echo "<span class=\"time-right\">" . $row['username'] . "</span>";

            echo "</div>";
         }
         mysqli_free_result($result);
      } else {
         echo "No records matching your query were found.";
      }
   } else {
      echo "ERROR: Could not able to execute $sql. " . mysqli_error($con);
   }
   mysqli_close($con);
?>

2 个答案:

答案 0 :(得分:0)

您可以使用变量来存储类值,并在第一次迭代后更改它。

$class = 'right' ;
while($row = mysqli_fetch_array($result)) {
    echo "<div class=\"container\">";
    if ($row['username'] == 'brother' ) {
        echo "<img src=\"images/" . $row['photo'] . "\" class=\"$class\" >";
    } else {
        echo "<img src=\"images/" . $row['photo'] . "\" class=\"$class\" >";
    }
    $class = 'left'; // change from 'right' to 'left'

或者您可以使用布尔值并在每次迭代时反转它。然后使用三元条件创建“左”或“右”类:

$right = true ;
while($row = mysqli_fetch_array($result)) {
    echo "<div class=\"container\">";
    if ($row['username'] == 'brother' ) {
        echo "<img src=\"images/" . $row['photo'] . "\" class=\"".($right?'right':'left')."\" >";
    } else {
        echo "<img src=\"images/" . $row['photo'] . "\" class=\"".($right?'right':'left')."\" >";
    }
    $right = !$right; // invert each time

答案 1 :(得分:0)

尝试这一点确保它对您有所帮助。 谢谢你

<?php include 'db.php'; $sql = 'SELECT * FROM users'; if($result = mysqli_query($con, $sql)) {
  if(mysqli_num_rows($result) > 0) {


     while($row = mysqli_fetch_array($result)){
        echo "<div class='container'>";


          if ($row['username'] == 'brother' ) {

echo "<img src='images/'" . $row['photo'] . "class='right'>";
} else {
    echo "<img src='images/'" . $row['photo'] . "class='left' >";
}

    echo "<span class='time-right'>" . $row['username'] . "</span>";

        echo "</div>";
     }
     mysqli_free_result($result);
  } else {
     echo "No records matching your query were found.";
  } } else {
  echo "ERROR: Could not able to execute $sql. " . mysqli_error($con);  }  mysqli_close($con); ?>