dps43633 2017-02-16 12:18
浏览 52
已采纳

mysql获取assoc数组空错误

I want to output the fetched array onto the frontend. It works fine until the array returns as empty. It throws a PHP error that 'undefined variable $data on php line X'. I've looked for solutions though they have not fully suited what I have in mind. Please assist.

public function search($search) {
    try {
        $query = $this->connection->prepare ( "SELECT * FROM files WHERE number=$search ORDER BY id" );
        $query->execute ();
        while ( $row = $query->fetch ( PDO::FETCH_ASSOC ) ) {
            $data [] = $row;
        }
        return $data;
    } catch ( PDOException $e ) {
        $e->getMessage ();
    }
}
  • 写回答

1条回答 默认 最新

  • donglian2106 2017-02-16 12:22
    关注

    You are running your query wrong way.

    The only proper way to add a variable into PDO query is to add it through a parameter. It is very important to understand that simply adding quotes around a variable is not enough and will eventually lead to innumerable problems, from syntax errors to SQL injections. On the other hand, due to the very nature of prepared statements, it's a bullet-proof solution that makes it impossible to introduce any problem through a data variable.

        $this->connection->prepare ( "SELECT * FROM files WHERE number=? ORDER BY id" );
        $query->execute ([$search]);
    

    while to eliminate the error you should use the appropriate fetch mode. So the full code would be

    public function search($search) {
        $this->connection->prepare ( "SELECT * FROM files WHERE number=? ORDER BY id" );
        $query->execute ([$search]);
        return $query->fetchAll(PDO::FETCH_ASSOC);
    }
    

    note that you should never catch an error to report it

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码