简体   繁体   中英

Fatal error: Cannot use object of type PDO as array

Here is the error Log

Fatal error: Cannot use object of type PDO as array in /Applications/XAMPP/xamppfiles/htdocs/php/blog/single.php on line 13

Here is 13 number line

$post = DB\query('SELECT * FROM posts WHERE id = :id LIMIT 1', array('id'   =>  $_GET['id']), $conn [0] ); 

i got this error when i try to get post title.

<?= $post['title'];?>

Full Code

<?php 

require 'functions.php';

use blog\DB;
// Connect to the DB
$conn = DB\connect($config);

if( !$conn ) die('Problem Connecting to the DB');

// Fetch all the posts

$post = DB\query('SELECT * FROM posts WHERE id = :id LIMIT 1', array('id'   =>  $_GET['id']), $conn [0] ); 
// Filter throgh and display in the view
$view_path = 'views/single.view.php';
include 'views/layout.php';

Instead of $conn[0] , Try using $conn .

For future issues, always remember you can output the datatypes, content, and structures of variables in php .

  1. Use the following to output the content in human readable format.

     echo "<pre>"; print_r($variable); echo "</pre>"; die(); 
  2. Use the following to output the content with datatype and extra info

     echo "<pre>"; var_dump($this); echo "</pre>"; die(); 
  3. Remember functions like gettype() etc.

Also based on your further comments, I'd recommend that you first grab a book or an online course of the language.

About your next error, remember that in php the variable needs to be defined before you can call/use it.

So on the line, where you care calling $post['title']; remember to first make sure that that variable is defined and has the index that you intend to call. Also use the above snippets to verify and you should be writing the handling code if that index is not set.

something like..

if(isset($post) && !empty($post) && isset($post['title'])) {
....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM