PHP if / else语句函数问题

时间:2013-06-24 23:23:42

标签: php sql if-statement

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

我对if 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);

?>

2 个答案:

答案 0 :(得分:0)

你的逻辑错误:

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

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

这是因为第一个条件完全包含了替代条件。 ie 如果数字不大于零,则肯定不会大于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>

答案 1 :(得分: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>

 <?}?>