PDO Query Database ODBC

╄→尐↘猪︶ㄣ 提交于 2019-12-11 17:50:55

问题


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();
    } 
?>

What is Uid? and what value should I enter?

And, about the query

<?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();
    }
?>

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

can you tell me why?


回答1:


For your second question:

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

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

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
}



回答2:


Uid is Username with which you want to connect to database, if your mdb file is not protected you may omit this parameter.

To fetch all results you have to use fetchAll (http://php.net/manual/en/pdostatement.fetchall.php).



来源:https://stackoverflow.com/questions/11026002/pdo-query-database-odbc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!