dqwh1209 2010-06-16 19:55
浏览 7

用于处理大多数数据库查询的PHP函数存在结果问题。 我得到了正确的行数,但它们都是一样的

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 result 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;
}
  • 写回答

1条回答 默认 最新

  • dounuo1881 2010-06-16 20:11
    关注

    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().

    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line