doujia9833 2014-06-17 02:30
浏览 78
已采纳

使用PDO获取MySQL数组时出错[重复]

This question already has an answer here:

I've been trying to convert my application from the old mysql syntax to PDO and it's been a real pain. Right now i'm having trouble as it seems like the same query using PDO is coming up empty as one that returned a full array using mysql_fetch_array

Here is the code for one of my functions:

//Get all contacts from DB
public function getContacts($regId) {
    try {
        $sql = "SELECT contacts FROM gcm_users WHERE gcm_regid = '$regId'";
        $resource = $this->db->query($sql);
        //$resource = mysql_query("SELECT contacts FROM gcm_users WHERE gcm_regid = '$regId'");      
        $resultArray = $resource->fetch(PDO::FETCH_ASSOC);
        $result = $resultArray[0];
        }

    catch (SQLException $e) {
        $output = 'Error fetching contacts: ' . $e->getMessage();
    }
    return $result;
}

The original mysql_query which worked fine is commented out. The error i'm currently receiving with this is:

Notice: Undefined offset: 0 in C:\xampp\htdocs\gcm\db_functions.php on line 197

Which leads to my

$result = $resultArray[0];

I looked up the error and it seems to be because the $resultArray is empty. I'm not used to using the PDO::FETCH_ASSOC instead of mysql_fetch_array, so i'm assuming the problem is in there somewhere.

</div>
  • 写回答

1条回答 默认 最新

  • dongqiangteng7319 2014-06-17 02:37
    关注

    You're using PDO::FETCH_ASSOC, which retrieves your result set row into an associative array (that is, an array with named elements like $resultArray['contacts'].

    You seem to want a numbered array. Use PDO::FETCH_NUM instead to get that.

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

报告相同问题?

悬赏问题

  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题