I'm learning PHP by following a book and experimenting a little.
The book (PHP & MySQL Novice TO Ninja 6th Ed) gives an example of displaying all the entries in a database column, by looping through the results.
I am trying to just display one of the entries and can't get it to work:
<?php
try {
$pdo = new PDO('mysql:host=localhost;dbname=ijdb', 'ijdbuser', 'mypassword');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT `joketext` FROM `joke` WHERE id = :id';
$statement = $pdo->prepare($sql);
$statement->execute( ['id' => 1] );
$text = $pdo->fetchColumn();
$output = $text;
this a controller and I have another template echoing $output.
At the moment I get the following error message:
Fatal error: Uncaught Error: Call to undefined method PDO::fetchColumn() in /home/vagrant/Code/Project/public/index.php:13 Stack trace: #0 {main} thrown in /home/vagrant/Code/Project/public/index.php on line 13
I'm not familiar with the FetchColum method, but have taken this code from a seperate tutorial I found online.
Any help would be much appreciated
Cheers
CodePudding user response:
The fetchColumn()
method belongs to the PDOStatement object and not the PDOConnection object.
So
<?php
try {
$pdo = new PDO('mysql:host=localhost;dbname=ijdb', 'ijdbuser', 'mypassword');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT `joketext` FROM `joke` WHERE id = :id';
$statement = $pdo->prepare($sql);
$statement->execute( ['id' => 1] );
$text = $statement->fetchColumn();
$output = $text;
CodePudding user response:
by ezsql you can select a column from table
$db->get_col
-- get one column from query (or previously cached results) based on column offset
$db->get_col_info
-- get information about one or all columns such as column name or type refrence link