PHP使用方法的返回值作为查询函数的参数


PHP issue using a method's return value as a parameter for query function

我有一个函数查询:

function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
    $args[$i] = urldecode($args[$i]);
    $args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
    $rows = array();
    if ($result!==true)
    while ($d = mysqli_fetch_assoc($result)) {
        array_push($rows,$d);
    }
    //return json
    return array('result'=>$rows);
} else {
    //error
    return array('error'=>'Database error');
}
    }

当我像这样使用它时,函数工作得很好:

$g = "05%";
$result = query("SELECT * FROM table_name WHERE table_column LIKE '%s'", $g);
print json_encode($result);

然而,当$g是从方法中检索到的值时,我没有得到结果。例如,假设我有一个来自类Date的getMonth()方法,该方法在回显时返回当前5月的05%。我尝试下面的代码,从数据库中一无所获:

$time = new Date();
//$g = "05%"; this would definitely get results from the db
$h = $time->getMonth();
echo $h; //this displays 05% on the screen
$result = query("SELECT * FROM table_name WHERE table_column LIKE '%s'", $h);
print json_encode($result);
我很确定我犯了一个简单的错误,但我似乎不明白是怎么回事。我该如何解决这个问题?

做一些事情,让你的方法只从05%返回05部分。然后在后面加上%例如

$h = $time->getMonth(); 
$h = "$h%";

然后就可以了