I'm trying to fetch values from one table column of a MySQL db with PHP (PDO), but I have two errors in the same line, this is the line (line 7):
$query = $dbh->prepare("SELECT * FROM table_name");
And these are error messages:
Notice: Undefined variable: dbh in ... on line 7
Fatal error: Call to a member function prepare() on a non-object in ... on line 7
My complete code:
1) file config.php
<?php
$host = "localhost";
$db_user = "user";
$db_psw = "pass";
$db_name = "database";
?>
2) file connection.php
<?php
include("config.php");
//collegamento
$col = "mysql:host=$host;dbname=$db_name";
try {
//tentativo di connessione
$db = new PDO($col , "$db_user", "$db_psw");
}
//gestione errori
catch(PDOException $e) {
echo 'Attenzione errore: '.$e->getMessage();
}
?>
3) file display-values.php (error in line 7)
<?php
// richiamo lo script responsabile della connessione a MySQL
require 'connection.php';
?>
<?php
$query = $dbh->prepare("SELECT * FROM table_name");
$query->execute();
$result = $query->fetchall();
?>
<?php
echo
"<table border='2'>
<tr>
<th>ID</th>
<th>A Number</th>
<th>First Name</th>
<th>Last Name</th>
<th>Why</th>
<th>Comments</th>
<th>Signintime</th>
</tr>"
;
foreach($result as $row)
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td><a href=Student.php?studentA_num=" . $row['anum'] . ">" .$row['anum'] . " </a></td>";
echo "<td>" . $row['first'] . "</td>";
echo "<td>" . $row['last'] . "</td>";
echo "<td>" . $row['why'] . "</td>";
echo "<td>" . $row['comments'] . "</td>";
echo "<td>" . $row['signintime'] . "</td>";
echo "<td> <input type=\"button\" value=\"Start Session\"onClick=\accept.php?id=" . $row['id'] . "&start=true></td>";
}
echo "</tr>";
echo "</table>";
?>
Note: In this code I've tried to fetch all values (just for a test), but I need to fetch data from one column "name_column" only, so how can I fix the two errors and edit the code to extract values from a specific column?
Thanks in advance!
Your PDO object is db
not dbh
The error states that:
Notice: Undefined variable: dbh in ... on line 7
PHP couldn't find an initialized variable called dbh, so dbh is undefined variable, therefore you have your notice here.
Fatal error: Call to a member function prepare() on a non-object in ... on line 7
As your code calls a method on a non existent variable, PHP is yelling this second error.
To sum up, you just need to change
$query = $dbh->prepare("SELECT * FROM table_name");
for
$query = $db->prepare("SELECT * FROM table_name");
Editing query for fetching values from 2 columns:
If you want to fetch values for 2 column only, just change your SQL query:
$query = $db->prepare("SELECT column_name_1, column_name_2 FROM table_name");
With this query you're selecting values from column_name_1 and column_name_2
I recommend you to take some basic SQL tutorial
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments