PDO查询数据库ODBC [英] PDO Query Database ODBC

查看:96
本文介绍了PDO查询数据库ODBC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从phpro.org学习有关PDO的方法,并且有些困惑.

I'm on my way learning about PDO from phpro.org, and a little bit confuse.

<?php
try {
    $dbh = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\pdo-tutorial.mdb;Uid=Admin");
    }
catch (PDOException $e)
    {
    echo $e->getMessage();
    } 
?>

什么是Uid?以及我应该输入什么值?

然后,关于查询

<?php

try {
    $dbh = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\pdo-tutorial.mdb;Uid=Admin");
    /*** echo a message saying we have connected ***/
    echo 'Connected to database<br />';

    /*** The SQL SELECT statement ***/
    $sql = "SELECT * FROM animals";

    /*** fetch into an PDOStatement object ***/
    $stmt = $dbh->query($sql);

    /*** echo number of columns ***/
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    /*** loop over the object directly ***/
    foreach($result as $key=>$val)
    {
    echo $key.' - '.$val.'<br />';
    }

    /*** close the database connection ***/
    $dbh = null;
}
catch(PDOException $e)
    {
    echo $e->getMessage();
    }
?>

我正在使用odbc,但是为什么foreach函数只是回显第一行,而不是循环回显数据库中所有的值?这是结果.

I'm using odbc, but why the foreach functions just echo the first row, not looping echoing all my value in the database? here are the result.

Connected to database
ID - 1
animal_type - kookaburra
animal_name - bruce

你能告诉我为什么吗?

推荐答案

第二个问题:

您需要使用fetchAll()而不是fetch(),这一次只能提供一行.

You need to use fetchAll() instead of fetch(), which only gives you one row at a time.

在您的代码中,尝试: $result = $stmt->fetchAll(PDO::FETCH_ASSOC);(尽管这会改变您的foreach循环的样子).

In your code, try: $result = $stmt->fetchAll(PDO::FETCH_ASSOC); (though that will change what your foreach loop looks like).

或者,您可以使用while循环按需提取每一行:

Alternatively, you can use a while loop to fetch each row as you need it:

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    //Do something with $row
}

这篇关于PDO查询数据库ODBC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆