函数总是返回零

时间:2014-12-02 17:28:32

标签: php mysql function

a.php

include 'function.php';

$avg = get_ecomm_avg_rating();
echo "Avg rating :- $avg";

function.php

$conn = mysqli_connect("myserver","abc","red", "live");

if (mysqli_connect_errno()) 
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

function get_ecomm_avg_rating()
{
    $query = "SELECT AVG(ROUND((r.ratings_sum / r.ratings_qty),1)) AS total_rating
        FROM abc AS c, xyz AS r
        WHERE c.store
        IN (994,094) 
        AND r.reviewid = c.id
        AND c.published =  '1'";

    $avg_rating_result = mysqli_query($conn,$query); 
    $avg_rating_row = mysqli_fetch_array($avg_rating_result); 
    $avg_rating_count = $avg_rating_row[0];
    $avg_rating_count_final = number_format($avg_rating_count, 1);

    return $avg_rating_count_final;

}

始终返回0.0。我该怎么办?任何击球手方法?我是新功能和PHP

1 个答案:

答案 0 :(得分:3)

变量范围存在问题,函数中不存在var $conn

您需要通过参数添加此var:

function get_ecomm_avg_rating($conn, $storeno) {
    ....
}

// and here when calling the function you pass there a DB connection
$avg = get_ecomm_avg_rating($conn);

// $conn has to be defined elsewhere, like $conn = mysqli_connect(...)

然后,您有未使用的参数$storeno