duanliushua5026 2018-11-22 22:45
浏览 39
已采纳

审查具有变量函数的系统

so basically I am trying to create a little thing where it outputs stars, based on the database saved rating integer. The problem is it does not seem to put the number I from the database, in the variable. Here is the code I used:

 <?php
$productID = 100;
$con = mysqli_connect("localhost", "root", "", "example");
function connect()
{
    $con = mysqli_connect("localhost", "root", "", "example");
    // Check connection
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    } else {
     return $con;
    }
}

function getStars($con)
{
    $productID = 100;
    $sql       = "SELECT rating
       FROM reviews
      -- JOIN stockitemstockgroups USING (StockItemID)
      -- JOIN stockgroups USING (StockGroupID)
       WHERE reviewID = '5'
       ";
    $result    = $con->query($sql);

    if ($con && ($result->num_rows > 0)) {
        // output data of each row
        while ($row = $result->fetch_assoc()) {
            echo $row["rating"];
        }
    } else {
        echo "error";
    }
}
$value = getStars($con);
echo $value;
for ($x = 1; $x <= $value; $x++) {
echo '<div class="rating"><span>&#9733;</span></div>';
}
?>
  • 写回答

1条回答 默认 最新

  • dongtong848825 2018-11-22 22:51
    关注

    I'm having trouble finding a duplicate, though I'm sure this is one. You aren't returning anything from your function, so $value doesn't have a value.

    function getStars($con)
    {
        $productID = 100;
        $sql       = "SELECT rating FROM reviews WHERE reviewID = 5";
        $result    = $con->query($sql);
    
        if ($result && ($result->num_rows > 0)) {
            // output data of first row
            $row = $result->fetch_assoc();
            return $row["rating"];
        } else {
            return false;
        }
    }
    

    As a general rule, never echo from a function. Also, no need for a loop over what will presumably be a single result.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line