There is such a code:

<?php $title='Post'; $back="index.php"; $logotext= "Post"; $home= "../index.php"; require "header.php"; function get_post_by_id($id) { //Здесь я создал функцию которая получает статью по ее id. global $db; $posts = $db->query("SELECT * FROM posts WHERE id = $id"); foreach ($posts as $post) { return $post; } } ?> <?php $post = get_post_by_id($_GET['id']); ?> 

And it gives the error: Fatal error: Uncaught Error: Call to a member function query () fullPost.php (20): get_post_by_id (NULL) # 1 {main} thrown in C: \ OSPanel \ domains \ rus \ fullPost.php on line 12

12 line is a line: $posts = $db->query("SELECT * FROM posts WHERE id = $id");

Please help ... Thanks in advance.

  • Where does the $ db object come from? Most likely, it is empty - Grulex
  • You have sent a null to the get_post_by_id method to the $ id place; therefore this is an error: function get_post_by_id ($ id = 0) {global $ db; $ posts = $ db-> query ("SELECT * FROM posts WHERE id =". $ id); foreach ($ posts as $ post) {return $ post; }} - Zohid
  • The $ db variable is taken from another file and is defined as the global $ dbhost = "127.0.0.1"; $ username = "root"; $ password = ""; $ dbname = "historylifensk"; $ db = new PDO ("mysql: host = $ dbhost; dbname = $ dbname", $ username, $ password); - HistoryLife NSK
  • @HistoryLifeNSK and this file is connected? The error means that there is no $db at the time of calling the query . - Yegor Banin
  • That's it, I figured it out, thank you so much for everything that was left unattended) - HistoryLife NSK

1 answer 1

Your error means that you do not pass the $ id parameter to the get_post_by_id function (it is passed to NULL), the global variable $ db has not been previously declared, therefore it is also NULL.

You need to debug the code in the places where $ db is declared, and also to call the get_post_by_id function and pass the $ id parameter for errors. It is likely that you have an error when connecting dependent files, as a result of which, the part of the code where the announcement takes place does not actually connect, causing similar errors.