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
}