user3287726
user3287726

Reputation: 27

Select data from database with PDO

I have some data in a mysql database.The database every time consists of a different number of rows.

An example of my table would be :

id  team1  team2  home  away  tip
----------------------------------
12   xxx    yyy   zzz   kkk
43   xxx    yyy   zzz   kkk
.     .      .     .     .
.     .      .     .     .

So what i need to do is loop through every row of the table and be able to get the data from that row so i can create the tip.

I am a bit confused on how i could do that with pdo.

What i ve tried so far is try to get a column of data like this:

$stmt = $db->prepare("SELECT id FROM tablename");
    $stmt->execute();
    $result=$stmt->fetchColumn();
    echo $result[0];

But even that , that i would expect to give me back the first id , which is 12 in this case, just returns me 1. Any ideas here?

Upvotes: 1

Views: 4590

Answers (5)

Humphrey
Humphrey

Reputation: 2817

if you want to loop throught you can use the while loop and below is the example

<?php 

$stmt =("SELECT id FROM tablename");
$result=$db->prepare($stmt );
$result->execute();
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
$id = $row['id'];
 echo $id;
}
?>

Upvotes: 0

Marc Kline
Marc Kline

Reputation: 9409

Use fetch (with FETCH_NUM) instead of fetchColumn

$stmt = $db->prepare("SELECT id FROM tablename");
    $stmt->execute();
    $result=$stmt->fetch(PDO::FETCH_NUM);
    echo $result[0];

Upvotes: 0

user849001
user849001

Reputation:

$stmt = $db->prepare("SELECT id FROM tablename");
try{
    $stmt->execute();
}catch(PDOException $err){
    //some logging function
}
//loop through each row
while($result=$stmt->fetch(PDO::FETCH_ASSOC)){
    //select column by key and use
    echo $result['id'];
} 

alternatively you could use fetchAll to select whole dataset into a variable. Then you wouldn't need to loop

Heres a useful resource for PDO:

http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

Upvotes: 2

iubema
iubema

Reputation: 349

Try to print the result without index

$stmt = $db->prepare("SELECT id FROM tablename ORDER BY id ASC");
$stmt->execute();
$result = $stmt->fetchColumn();
echo $result;

Upvotes: 0

Ferrakkem Bhuiyan
Ferrakkem Bhuiyan

Reputation: 2783

$getUsers = $DBH->prepare("SELECT * FROM tablename ORDER BY id ASC");
$getUsers->execute();
$users = $getUsers->fetchAll();

May be helps you

Upvotes: 0

Related Questions