dongpa5207 2014-03-24 18:22
浏览 66
已采纳

将数据从MySQL拉入JSONArray(使用PDO!)

I was reading something on the Internet and many people say that it's recommended to switch to PDO from old mysql (and mysqli) extensions.

I'm new with this PDO, I learned something about it. For my problem I tried to search stackoverflow, Google, etc, but it didn't helped me.

Original script with mysqli :

$data = mysqli_query($con, "SELECT x1, x2, x3, x4 FROM Table1 WHERE x1 = $variable1");
$row = mysqli_fetch_row($data);
$result_data = array(
  'data1' => $row[0],
  'data2' => $row[1]
 );

echo json_encode($result_data);

This code outputs something like this :

{"data1", 1, "data2", 2}

I tried to change it with this PDO code :

 $STH = $DBH->prepare("SELECT x1, x2, x3, x4 FROM Table1 WHERE x1 = ?");
 $STH->bindParam(1, $variable1);
 $STH->execute();
 $row = $STH->fetchAll();

 $result_data = array( 
    'data1' => $row[0],
    'data2' => $row[1],
 ); 

  echo json_encode($result_data);

This back me something very strange like

{"data1", 1, 2, 1, "data2", 1, "data2"}, data1 null, data2 null

It should back like with original mysqli script...

I tried with multiple fetch modes like assoc, num, column, what I was found on Internet, but result was very similar and I always get this error :

Notice:Undefined offset: 1 in

What can be the problem, how to fix it?

  • 写回答

1条回答 默认 最新

  • doutuo3935 2014-03-24 18:25
    关注
     $STH = $DBH->prepare("SELECT x1 data1, x2 data2 FROM Table1 WHERE x1 = ?");
     $STH->execute([$variable1]);
     echo json_encode($STH->fetchAll(PDO::FETCH_ASSOC));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了