包含在函数中时,php语句无法正常工作

时间:2015-12-14 17:51:05

标签: php function mysqli

下面的代码在没有包含在函数

中时工作正常
$opt = 'logo_img';
$sql="SELECT option_value FROM r0_options WHERE option_name='".$opt."'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_NUM);
var_dump($row);

但是,当我执行以下操作并调用该函数时,它会给出NULL。

function get_result($opt){
    $sql="SELECT option_value FROM r0_options WHERE option_name='".$opt."'";
    $result=mysqli_query($db,$sql);
    $row=mysqli_fetch_array($result,MYSQLI_NUM);
    var_dump($row);
}

get_result('logo_img');

2 个答案:

答案 0 :(得分:1)

It's because you are not passing $db variable, either pass it to function or do the following:

function get_result($opt){
    global $db;

    $sql="SELECT option_value FROM r0_options WHERE option_name='".$opt."'";
    $result=mysqli_query($db,$sql);
    $row=mysqli_fetch_array($result,MYSQLI_NUM);
    var_dump($row);
}

get_result('logo_img');

答案 1 :(得分:0)

You are forgotten to pass he '$db' to your function:

function get_result($db, $opt){