Reputation: 25
I know this is probably something simple, but I have searched for hours the past few days and I'm ready to jump out of my one-story building.
Was using mysqli_ or mysql_ style in the php to access the data for a while with no luck.. Have since been reading about PDO and found numerous tutorials on how to use it. I feel like what I'm trying to do should be so simple but I've tried copying what I've found on this site and other tutorials to the T and the site still does not display the data.
try {
$conn = new PDO("mysql:host=$hostname; dbname=$userdb", $username, $password);
$conn->exec("SET CHARACTER SET utf8");
$sql = "SELECT * FROM Monday";
$result = $conn->query($sql);
while($row = $result->fetchAll(PDO::FETCH_ASSOC)) {
echo $row['Name'] . '<br />';
}
$conn = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
Basically the website will display everything after the first -> in this case after the $conn-> but none of the actual table data.
I've tried about 50 different ways at least from numerous sites and I'm just lost now I guess..
Side note: I do have php forms on the same site that when submitted successfully insert data into the table, so I know I am able to connect to the db and table and INSERT, its just the issue of SELECT I can't get.
Thanks for any help
EDITED: to add fetchAll
Upvotes: 0
Views: 290
Reputation: 6896
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
Should be;
while($row = $result->fetchAll(PDO::FETCH_ASSOC)) {
Upvotes: 0
Reputation: 479
You are using the method fetch()
in your loop, which only fetches the next single row of your results. Replace it with fetchAll()
and it should work.
More information about the fetchAll()
method:
http://php.net/manual/en/pdostatement.fetchall.php
And for testing purposes you could set the PDO error mode to PDO::ERRMODE_EXCEPTION
. See: http://php.net/manual/en/pdo.error-handling.php
Upvotes: 2