开发者

PHP function to handle most database queries has a problem with results. I am getting the right number of rows but they are all the same

Here is my little function. It does not handle the results correctly. I do get all the rows that I want, but all the rows of the $results array contain the exact same values.

So i make 2 arrays, a temporary array to hold the values after each fetch, and another array to hold all the temporary arrays.

First i take the temp array and map its keys to the column names. Then i give it to bind_result, and call fetch() and use it like I would any other res开发者_Go百科ult value.

Could this be because I re-use the $results array?

numresults is the number of values you are taking from each row. if 0, you are not getting any results back.

function db_query($db, $query, $params = NULL, $numresults = 0)
{
    if($stmt = $db -> prepare($query))
    {
        if($params != NULL)
        {
            call_user_func_array(array($stmt, 'bind_param'), $params);
        }
        if(!$stmt -> execute())
        {
            //echo 'exec error:',$db->error;
            return false;
        }
        if($numresults > 0)
        {
            $results = array();
            $tmpresult = array();
            $meta = $stmt->result_metadata();
            while ($columnName = $meta->fetch_field())
                $tmpresult[] = &$results[$columnName->name];

            call_user_func_array(array($stmt, 'bind_result'), $tmpresult);       
            $meta->close(); 
            $results = array();
            while($stmt -> fetch())
                $results[] = $tmpresult;
        }
        $stmt -> close();
    }
    else
    {
        //echo 'prepare error: ',$db->error;
        return false;
    }
    if($numresults == 0)
        return true;
    return $results;
}


You need to copy the values out of $tmpresult one element at a time. Replace this:

$results[] = $tmpresult;

With this:

$tmpresultcopy = array();
foreach ($tmpresult as $key => $value) {
    $tmpresultcopy[$key] = $value;
}
$results[] = $tmpresultcopy

What you're doing now is just copying the references. So you end up with $results storing N copies of the same set of references.

This is one of the reasons I recommend using PDO instead of mysqli! It's so much easier to use PDOStatement::fetchAll().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜