问题
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