0

我创建了一个 css3 进度条。我想很好,所以如果用户有示例 3 喜欢/点,它说:14%,如果有 5,它说 29%(这只是一个例子)。

我对 if 和 else 很陌生,所以我认为我用错了。它下面的代码只显示“1 like”。

代码如下:

<?php

session_start();
$con=mysqli_connect("localhost","root","","facebook");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

  $username = $_SESSION['username'];




$result = mysqli_query($con,"SELECT likes FROM login where username='".$username."'");

while($row = mysqli_fetch_array($result))


if($row['likes'] > 0) { ?>


<div class="meter animate" align="left">
    <span style="width: 14%"><span>1 likes </span></span>
</div>

<?php
} else if($row['likes'] > 1){ ?>
<div class="meter animate" align="left">
    <span style="width: 28%"><span>2 likes </span></span>
</div>

<?php
}
mysqli_close($con);

?>
4

2 回答 2

0

你的逻辑不正确:

if ($row['likes'] > 0) {

} elseif ($row['likes'] > 1) {
    // This will never be entered
}

那是因为第一个条件完全包含了替代条件。 如果数字不大于零,那么它肯定不大于1。

目前尚不清楚您是否需要分支。这有什么问题:

<div class="meter animate" align="left">
    <span style="width: <?php some_width_calculation_here() ?>%"><span>
       <?php print($row['likes'] . ($row['likes'] == 1 ? "like" : "likes")); ?>
    </span></span>
</div>
于 2013-06-24T23:27:36.960 回答
0

您需要一个数字来比较它们likes,以便获得准确的百分比......例如,有多少喜欢构成 100%?

我会这样做...

if($row['likes'] > 0) { 

 $likes = intval($row['likes']);
 $total = 20;  //ex....whatever number constitutes 100%;
 $width = (($likes / $total)*100)."%"; 
 ?>

//So if in this case you have 5 likes,   (5/20)*100 = 25
//$width would be set to 25%

 <div class="meter animate" align="left">
<span style="width: '<?echo $width;?>'"><span><?echo $row['likes'];?> likes </span></span>
 </div>

 <?}?>
于 2013-06-24T23:27:41.747 回答