douzhimei8259 2015-04-26 21:14
浏览 117
已采纳

如何从查询生成的数组中正确获取数据

I'm generally confused about the proper way to get data from a query once you execute. My end goal is to be able to show a list of all the records, but I'm not sure how to do it. I've tried a couple of different things but none have given me quite what I'm looking for. For example, when I search for Batman (which should have a record for [Batman, 500, 1993], and a record for [Batman, 499, 1993]) here's what I've tried:

$search->execute();

$result = $search->fetch(PDO::FETCH_ASSOC);
print_r($result);

Which gives me: Array ( [comicTitle] => Batman [comicIssue] => 500 [releaseDate] => 1993 )

That's more or less the format I'm looking for except that it's only one record instead of all of them.

$search->execute();

$result = $search->fetchAll(PDO::FETCH_ASSOC);
print_r($result);

Which gives me: Array ( [0] => Array ( [comicTitle] => Batman [comicIssue] => 500 [releaseDate] => 1993 ) [1] => Array ( [comicTitle] => Batman [comicIssue] => 499 [releaseDate] => 1993 ) )

$search->execute();

$result = $search->fetch(PDO::FETCH_ASSOC);
foreach($result as $row) {
        echo $row['comicTitle']."<BR>";
        echo $row['comicIssue']."<BR>";
        echo $row['releaseDate']."<BR>";

This echos 3 B's, 3 5's, and 3 1's with an illegal string offset warning between each.

So if I wanted to echo a line reading

"Title: " . $whatevertitle . " Issue: " . $whateverissue . " Release: " $whateverelease

for each record found, how do I go about actually getting those values from the returned array?

  • 写回答

1条回答 默认 最新

  • dqp21271 2015-04-26 21:21
    关注

    using ->fetch(PDO::FETCH_ASSOC)

    $search->execute();
    
    while($row = $search->fetch(PDO::FETCH_ASSOC)){
            echo "Title: " . $row['comicTitle']."<BR>";
            echo "Issue: " . $row['comicIssue']."<BR>";
            echo "Release: " . $row['releaseDate']."<BR>";
    }
    

    using ->fetchAll(PDO::FETCH_ASSOC)

    $search->execute();
    
    $result = $search->fetchAll(PDO::FETCH_ASSOC);
    foreach($result as $row) {
            echo "Title: " . $row['comicTitle']."<BR>";
            echo "Issue: " . $row['comicIssue']."<BR>";
            echo "Release: " . $row['releaseDate']."<BR>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥50 Oracle Kubernetes服务器集群主节点无法访问,工作节点可以访问
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架
  • ¥15 有关sql server business intellige安装,包括SSDT、SSMS。
  • ¥15 stm32的can接口不能收发数据
  • ¥15 目标检测算法移植到arm开发板
  • ¥15 利用JD51设计温度报警系统