Fatal error call to a member function fetch on a non object in

I am just trying out PDO and I get this error, Fatal error: Call to a member function fetch() on a non-object, but isn't it already on the $this->db object? class shoutbox { private $db;

I am just trying out PDO and I get this error, Fatal error: Call to a member function fetch() on a non-object, but isn’t it already on the $this->db object?

class shoutbox {

    private $db;

    function __construct($dbname, $username, $password, $host = "localhost" ) 
    { # db conections
        try {
            $this->db = new PDO("mysql:host=".$hostname.";dbname=".$dbname, $username, $password);
        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
        }
    }

    function getShouts()
    {
        $sql_shouts = $this->db->query('SELECT shoutid, message, pmuserid, ipadress, time FROM shouts WHERE pmuserid == 0');

        return $sql_shouts->fetch(PDO::FETCH_OBJ);

    }

}

asked Jul 28, 2010 at 3:06

Carlos's user avatar

0

Look carefully at the documentation for PDO::query, particularly the «Return Values» section:

PDO::query() returns a PDOStatement
object, or FALSE on failure.

The important bit is «FALSE on failure». FALSE is not an object, so calling ->fetch() is bad news.

The error is probably due to your use of «==» comparison operator. In SQL, it’s just «=».

You should test that the $sql_shouts is not false, and then do something smart with the error, if there was one:

<?PHP
$sql_shouts = $this->db->query('...');
if ($sql_shouts === false){
    $errorInfo = $this->db->errorInfo();
    //log the error or take some other smart action
}
return $sql_shouts->fetch(PDO::FETCH_OBJ);

answered Jul 28, 2010 at 3:57

timdev's user avatar

timdevtimdev

61.2k6 gold badges82 silver badges92 bronze badges

1

I would say that your query is not executing due to incorrect syntax. You should really check PDO’s errorinfo static function to see if the query errored out or not.

Here is a potential correct SQL statement:

$sql_shouts = $this->db->query('SELECT shoutid, message, pmuserid, ipadress, `time` FROM shouts WHERE pmuserid = 0');

I believe Time is a reserved word in MySQL I would recommend using a different name but encasing it in backticks will alleviate that issue. 1 equal sign is used for mysql, not two. But yea, look into the errorinfo function to determine if your query failed due to a syntax error and handle it gracefully.

answered Jul 28, 2010 at 3:10

Jim's user avatar

JimJim

18.6k5 gold badges48 silver badges65 bronze badges

1

It happens when the table doesn’t exist also. make sure it actually exists, and isn’t just a holder in the database due to hard drive errors.

When that happens I suggest you recreate the database/table.

answered Jun 18, 2015 at 19:10

a coder's user avatar

a codera coder

5454 silver badges23 bronze badges

I got this error message due to a silly mistake with brackets. It was nested inside an if statement and just didn’t see it.

db_query("SELECT thing FROM table WHERE var=:var", array(":var" => $var)->fetchField());

It took me a while to work out that I didn’t close the db_query bracket in the right place. Maybe it helps someone else staring at this wondering wth. Correct:

db_query("SELECT thing FROM table WHERE var=:var", array(":var" => $var))->fetchField();

answered Dec 23, 2016 at 10:43

Paul's user avatar

PaulPaul

5687 silver badges23 bronze badges

PHP - Make URLs and Twitter Usernames in Text Links

When coding, it is always advisable you check code to make sure the syntax are correct as majority of bugs arises from it. If you are using an Integrated development environment (IDE) such as NetBeans, Dreamweaver or Aptana Studio, you are notified when there is (syntax) error in your code.

While working on a CMS I was building for a client, I encountered this PHP / MySQL error;

Fatal error: Call to a member function fetch_object() on a non-object in C:xampphtdocsuser_edit.php on line 7

Below is the code that resulted to that error;


 <?php 
$result = $mysqli->query("SELECT profile_picture FROM users WHERE id=('$user_id'"); 
	
	while ($rows = $result->fetch_object()) { 
            printf('<img src="%s" />', $rows->profile_picture); 
         }
  ?>

I inserted the code in NetBeans and Aptana Studio, no error was shown.

Taking a close look at the code, you will see there’s a syntax error in the SQL SELECT Query as the id wasn’t having a closing parenthesis.
It is the SQL syntax error that resulted to the Fatal error: Call to a member function fetch_object() on a non-object.

The correct SQL is:


$result = $mysqli->query("SELECT profile_picture FROM users WHERE id=('$user_id')"); 

It is best practice you check if the SQL query was successful before retrieving content from database.
For example:


<?php 
$result = $mysqli->query("SELECT profile_picture FROM users WHERE id=('$user_id')"); 
	
	if ($result) {
            
            while ($rows = $result->fetch_object()) { 
           
                printf('<img src="%s" />', $rows->profile_picture); 
         }
         
        }
        
        else {
            echo "Error with SQL";
        }
  ?>
Summary

We have seen from the article that the cause of Fatal error: Call to a member function fetch_object() on a non-object is as a result of mysqli_query returning FALSE on failure.

If you are using the depreciated mysql_fetch_array to retrieve the database content and you had similar above SQL query error, below is the error message you will get.

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:xampphtdocsuser_edit.php on line 7

Don’t miss out!

Subscribe To Newsletter

Receive the best WordPress, Git, Web development and programming tutorials.

Give it a try. You can unsubscribe at any time.

Function fetch_assoc() on a non-object

Одной из самых популярных ошибок, с которой мне и моим ученикам приходится сталкиваться, это «Function fetch_assoc() on a non-object«. Регулярно мне присылают вопросы с этой ошибкой и спрашивают, что делать. Давайте с Вами разберём основные причины возникновения данной ошибки.

В оригинале данная ошибка означает, что мы пытаемся вызвать метод fetch_assoc() у не объекта. Например, она возникнет здесь:

<?php
  $x = false;
  $x->fetch_assoc();
?>

У нас переменная «x» является булевской, поэтому никаких методов у неё нет, о чём и сообщает нам PHP. Но это базовая ошибка, которую вряд ли кто-то допустит. Поэтому чаще всего «Function fetch_assoc() on a non-object» является лишь следствием другой ошибки, на которую PHP не реагирует:

<?php
  $result_set = $mysqli->query("SELECT * FROM WHERE `id`='3'");
  $row = $result_set->fetch_assoc();
?>

У нас возникает всё та же ошибка, но теперь она не очевидна. Данная ошибка нам сообщает, что переменная «result_set» не является объектом. Движемся дальше, а почему она не является объектом, где мы её определили? Поднимаем глаза выше и видим, что в неё мы должны поместить результат выборки. И вот именно в этой строчке и содержится ошибка. Если бы $mysqli был не объектом, или мы бы ошиблись с написанием метода query(), нам бы PHP об этом сразу сообщил.

Следовательно, вся проблема в строковой переменной с запросом. Разумеется, на содержимое строки PHP никак не реагирует, но в этом запросе содержится ошибка. Внимательно к нему приглядевшись, можно заметить, что там не хватает названия таблицы.

Исправив запрос, ошибка «Function fetch_assoc() on a non-object» исчезнет. Как видите, в большинстве случаев данная ошибка возникает именно из-за неправильного запроса.

Цель данной статьи была не только рассказать об этой ошибке, но и показать, что не надо зацикливаться на той строке, где, как показывает PHP, содержится ошибка.

  • Создано 14.01.2013 10:54:00


  • Михаил Русаков

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления

Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

  1. Кнопка:

    Она выглядит вот так: Как создать свой сайт

  2. Текстовая ссылка:

    Она выглядит вот так: Как создать свой сайт

  3. BB-код ссылки для форумов (например, можете поставить её в подписи):

I’m using phinx for the first time and have followed the docs to setup a simple demo.

phinx.php

<?php
    include 'config/config.php';
    return array(
        "paths" => array(
            "migrations" => "%%PHINX_CONFIG_DIR%%/migrations"
        ),
        "environments" => array(
            "default_migration_table" => "phinxlog",
            "default_database" => "development",
            // $DBH - Database Handle, created in config.php for the correct environment
            "development" => array(
                "connection" => $DBH
            ),
            "staging" => array(
                "connection" => $DBH
            ),
            "production" => array(
                "connection" => $DBH
            )
        )
    );

20141223021531_initial_migration.php

<?php

use PhinxMigrationAbstractMigration;

class InitialMigration extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     *
     * Uncomment this method if you would like to use it.
     *
     */
    public function change()
    {
        // create the demo table
        $table = $this->table('demo');
        $table->addColumn('created', 'datetime', array('default' => 'CURRENT_TIMESTAMP'))
              ->addColumn('name', 'string', array('limit' => 20))
              ->create();
    }


    /**
     * Migrate Up.
     */
    public function up()
    {

    }

    /**
     * Migrate Down.
     */
    public function down()
    {

    }
}

When I run ./bin/phinx migrate -c phinx.php -e development, I get…

Phinx by Rob Morgan - https://phinx.org. version 0.4.0

using config file ./phinx.php
using config parser php
using migration path /vagrant/migrations
using environment development
PHP Fatal error:  Call to a member function fetch() on a non-object in /vagrant/vendor/robmorgan/phinx/src/Phinx/Db/Adapter/PdoAdapter.php on line 303

Fatal error: Call to a member function fetch() on a non-object in /vagrant/vendor/robmorgan/phinx/src/Phinx/Db/Adapter/PdoAdapter.php on line 303

I’m sure I’ve missed something obvious, though it’s eluding me at 2:52am!

Hope you can help.

Best regards

Pete

Запрос если напрямую к базе пременить отрабатывает нормально, возможно скрипт отправляет весь запрос в неверной кодировке, но тоже сомнительно.

Добавлено через 8 часов 51 минуту
Вопрос точно в кодировки передачи запроса, так как если я в переменную $findtext подставляю не строку а цыфры, скрипт отрабатывает, но вот вывод из базы на кирилице заменяется на ??????:

SELECT * FROM body WHERE `nomer_dog` LIKE «%1-13-302%» OR `adres_ob` LIKE «%1-13-302%»Array ( [0] => Array ( [id] => 143 [nomer_p_p] => 124 [rieltor] => ????????? ?.?. [nomer_dog] => 1-13-302-004 [data_dog] => 05-08-2013 [adres_ob] => ????????????, 17?-24 [fio_prod] => ????? ????????? ????????, ?????? ?????? ??????? [fio_pokup] => ???????? ?????? ?????????? [cena_ob] => 3060000 [srok_dog] => 01-09-2013 [d_sog_o_chem] => [d_sog_blank] => [d_sog_data] => [av_fl_blank] => [av_fl_data] => [av_fl_summa] => [av_fl_srok] => [av_fl_pokup] => [av_vladis_blank] => [vid_avans] => [data_polu_avans] => [period_avans] => [summa_avans] => [av_vladis_pokup] => [data_kassa] => [go_avans] => [rielt_pokup] => [pdkp_data] => [pdkp_srok] => [pdkp_av_summa] => [pdkp_zk_summa] => [uved_srok] => [uved_ok] => [dkp_data] => 15-08-2013 [dkp_c_offic] => 3060000 [dkp_c_real] => 3060000 [srok_osv] => [data_pered] => 25-08-2013 [data_avr] => [numer_avr] => [data_komis] => [arhiv] => [ras_ok] => [jurist_off] => [komiss] => 60000 [prim] => [global_data] => 08.2013 [ofis] => dobroe [color] => #57BFFD [tim_dat] => 2013-08-11 03:07:21 [ins_avtor] => ??????? ?.?. [last_autor] => ) [1] => Array ( [id] => 132 [nomer_p_p] => 114 [rieltor] => ????????? ?.?. [nomer_dog] => 1-13-302-004 [data_dog] => 05-08-2013 [adres_ob] => ????????????, ?. 17-?, ??. 24 [fio_prod] => ?????? ?????? ??????? ????? ????????? ???????? [fio_pokup] => [cena_ob] => 3060000 [srok_dog] => 01-09-2013 [d_sog_o_chem] => [d_sog_blank] => [d_sog_data] => [av_fl_blank] => [av_fl_data] => [av_fl_summa] => [av_fl_srok] => [av_fl_pokup] => [av_vladis_blank] => ?146 [vid_avans] => ?? ???????????? ??? ???????? (?? ???????) [data_polu_avans] => 05-08-2013 [period_avans] => 01-09-2013 [summa_avans] => 50000 [av_vladis_pokup] => ???????? ?????? ?????????? [data_kassa] => [go_avans] => [rielt_pokup] => [pdkp_data] => [pdkp_srok] => [pdkp_av_summa] => [pdkp_zk_summa] => [uved_srok] => [uved_ok] => [dkp_data] => [dkp_c_offic] => [dkp_c_real] => [srok_osv] => [data_pered] => [data_avr] => [numer_avr] => [data_komis] => [arhiv] => [ras_ok] => [jurist_off] => [komiss] => 60000 [prim] => [global_data] => 08.2013 [ofis] => dobroe [color] => [tim_dat] => 2013-08-05 18:08:21 [ins_avtor] => ??????? ?.?. [last_autor] => ) )

Как это исправить, остальные скрипты, которые обращаются к этой базе и вытаскивают результаты, отрабатывают нормально.

Добавлено через 1 час 47 минут
Решил вопрос, костыли конечно, но проблема была в кодировки указал явно в какой передавать в базу:

PHP
1
2
3
4
5
$query = "SELECT * FROM body WHERE $query_search";
    echo $query;
    $mysqli = new mysqli("localhost", "root", "motorola", "avans");
    mysqli_query($mysqli,"SET NAMES cp1251");
    $result_set = $mysqli->query($query);

  • #1

Последняя строчка кода не работает. Выдает сообщение Fatal error: Call to a member function fetch_row() on a non-object in Z:homeforumwwwindex.php

PHP:

$conn = mysqli_connect('localhost','root','');
$result = $conn->query("SELECT * FROM themes");
$row = $result->fetch_row();

grigori


  • #3

У меня PHP Version 5.3.3
Отладка-отладкой, но не работает очевидная вещь. Это должно работать. У кого была такая ситуация и кто знает как с ней бороться?

  • #5

PHP:

echo $result; // ничего не выводит

  • #7

Результат:
bool(false)

К БД подключается, т.к. нет ошибки. Если я ставлю пароль «1», то выдает ошибку, значит к БД коннектится нормально

  • #9

Вот это силища! Вот это дебаг так дебаг. Если вар дамп не сработает, то уж echo точно выведет.

  • #10

Спасибо всем.
Просто не была указана БД «forum».
Правильный запрос выглядит так

PHP:

$result = $conn->query("SELECT * FROM forum.themes");

  • #12

Смеетесь, ну почему-то в вышеизложенных сообщениях никто об этом не написал.

  • #13

как не написали? phpfaq.ru/debug — для тебя не ответ? там все как раз написано и про твой случай

PHP Fatal Error [FIX]: Call to a Member Function Fetch_Assoc On a Non-Object

  • By John Morris
  • May 18, 2016
  • PHP Code Snippets, Podcast
  • fatal error, php error

I remember this annoying error like it was yesterday.

It always baffled me a bit when I first started learning PHP (I know… N00B!): Fatal error: call to a member function fetch_assoc() on a non-object.

It was always the line number that tripped me up.

Anyhoo, here’s what’s really going on and how to kill this error dead once and for all:

And, if you’d give me a likey-like I’d sure appreciate it!

And like I said the source code is available on Patreon for the smart folks who support the show. (You know you wanna join them.)

P.S. If you liked the show, give it a like and share with the communities and people you think will benefit. And, you can always find all my tutorials, podcast episodes and more on johnmorrisonline.com, @jpmorris on Twitter and youtube.com/johnmorrisvideo.

Subscribe to the Podcast

[saf]

Who else wants to build a thriving freelance business?

I’ve helped 39,413 other freelancers start and grow thriving freelance businesses. Are you next? Subscribe to my Freelance Secrets newsletter and I’ll show you how.

You might also like

John Morris

JOHN MORRIS

I’m a 15-year veteran of freelance web development. I’ve worked with bestselling authors and average Joe’s next door. These days, I focus on helping other freelancers build their freelance business and their lifestyles.

Who else wants to build a thriving freelance business?

I’ve helped 39,413 other freelancers start and grow thriving freelance businesses. Are you next? Subscribe to my Freelance Secrets newsletter and I’ll show you how.

Success Stories

Ready to add your name here?

Tim Covello

Tim Covello

75 SEO and website clients now. My income went from sub zero to over 6K just last month. Tracking 10K for next month. Seriously, you changed my life.

Michael Phoenix

Michael Phoenix

By the way, just hit 95K for the year. I can’t thank you enough for everything you’ve taught me. You’ve changed my life. Thank you!

Stephanie Korski

Stephanie Korski

I started this 3 days ago, following John’s suggestions, and I gained the Upwork Rising Talent badge in less than 2 days. I have a call with my first potential client tomorrow. Thanks, John!

Jithin Veedu

Jithin Veedu

John is the man! I followed his steps and I am flooded with interviews in a week. I got into two Talent clouds. The very next day, I got an invitation from the talent specialists from Upwork and a lot more. I wanna shout out, he is the best in this. Thanks John for helping me out!

Divyendra Singh Jadoun

Divyendra Singh Jadoun

After viewing John’s course, I made an Upwork account and it got approved the same day. Amazingly, I got my first job the very same day, I couldn’t believe it, I thought maybe I got it by coincidence. Anyways I completed the job and received my first earnings. Then, after two days, I got another job and within a week I got 3 jobs and completed them successfully. All the things he says seem to be minute but have a very great impact on your freelancing career.

Sarah Mui

Sarah Mui

I’ve been in an existential crisis for the last week about what the heck I’m doing as a business owner. Even though I’ve been a business for about a year, I’m constantly trying to think of how to prune and refine services. This was very personable and enjoyable to watch. Usually, business courses like this are dry and hard to get through…. repeating the same things over and over again. This was a breath of fresh air. THANK YOU.

Waqas Abdul Majeed

Waqas Abdul Majeed

I’ve definitely learnt so much in 2.5 hours than I’d learn watching different videos online on Youtube and reading tons of articles on the web. John has a natural way of teaching, where he is passionately diving in the topics and he makes it very easy to grasp — someone who wants you to really start running your business well by learning about the right tools and implement them in your online business. I will definitely share with many of the people I know who have been struggling for so long, I did find my answers and I’m sure will do too.

Scott Plude

Scott Plude

I have been following John Morris for several years now. His instruction ranges from beginner to advanced, to CEO-level guidance. I have referred friends and clients to John, and have encouraged my own daughter to pay attention to what he says. All of his teachings create wealth for me (and happiness for my clients!) I can’t speak highly enough about John, his name is well known in my home.

Sukh Plaha

John is a fantastic and patient tutor, who is not just able to share knowledge and communicate it very effectively – but able to support one in applying it. However, I believe that John has a very rare ability to go further than just imparting knowledge and showing one how to apply it. He is able to innately provoke one’s curiosity when explaining and demonstrating concepts, to the extent that one can explore and unravel their own learning journey. Thanks very much John!

Mohamed Misrab

Misrab Mohamed

John has been the most important person in my freelance career ever since I started. Without him, I would have taken 10 or 20 years more to reach the position I am at now (Level 2 seller on Fiverr and Top Rated on Upwork).

Who else wants to build a thriving freelance business?

I’ve helped 39,413 other freelancers start and grow thriving freelance businesses. Are you next? Subscribe to my Freelance Secrets newsletter and I’ll show you how.

Latest Posts

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fatal error c1902 несоответствие диспетчера базы данных программы проверьте установленную копию
  • Fatal error c1859 непредвиденная ошибка предкомпилированного заголовка
  • Fatal error c1853
  • Fatal error c1510 cannot load language resource clui dll
  • Fatal error c1202

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии