Dwayne B
Dwayne B

Reputation: 107

Displaying data from a database using PDO

I've been staring at code for hours trying to see what I'm missing. Maybe someone can point me in the right direction.

First I have a database with multiple tables. One for images that stores the location and details of products. I've built pages that let me view, edit and add products. This all works great.

I'm now trying to do something simple and its not working. I created a table "Contacts" in the database and added the rows "name, street, city, zip, phone, email". I have populated this table with test data.

I'm trying to get my page to read the data and display it on the screen. I had wrote a complete page of html and screwed around with it trying to get it to work. after getting frustrated I resorted to a very simple php script below. I keep getting SQL error "Notice: Undefined index: name in C:\wamp\www\woody\Admin\index.php on line 38" I know the first index is called "name" I have also attempted to replace "$results['name']" with "$results['0']" and "$results['1']". Nothing seems to work. Anyone see what my tired eyes are missing?

<body>

<?php
    require_once("../includes/db.php");

$sql = "SELECT * FROM contact";
$query = $conn->prepare( $sql );
$query->execute();
$results = $query->fetchAll( PDO::FETCH_ASSOC );        


echo htmlentities($results['name']);


?>








<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>  

Upvotes: 1

Views: 3849

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157863

echo htmlentities($results[0]['name']);

would be correct way because you are using fetchAll() that returns a nested array.

or, more proper way as you are selecting many rows

foreach ($results as $row)
{
    echo htmlentities($row['name']);
}

If you want to select only one row, then you have to use fetch() method instead of fetchAll(). You may read about various fetch modes in the guide I wrote, The only proper guide on PDO

If empty array is returned, than you did not populated the table with sample data

There is also a possibility for the error. You have to report them as described in My PDO Statement doesn't work

Upvotes: 1

Related Questions