0

The code below was not working:

    public function __construct($thread_id)
    {
        require_once('../private/mysqli_connect.php');
        require_once('../php_classes/class_message.php');

        $this->thread_id=$thread_id;

        $q="SELECT *
        FROM message_thread_name
        WHERE thread_id=2";

        if($r=@mysqli_query($dbc, $q))
        {
            while($row=mysqli_fetch_array($r, MYSQLI_ASSOC))
            {
                $this->poster=$row['name'];
                $this->subject=$row['thread_subject'];
            }
        }

        $qm="SELECT message_id
        FROM message
        WHERE thread_id=$this->thread_id";

        if($rm=@mysqli_query($dbc, $rm))
        {
            while($rowm=mysqli_fetch_array($rm, MYSQLI_ASSOC))
            {
                $message=new message($rowm['message_id']);
                array_push($this->messages, $message);
            }
        }
    }

I ran out of ideas for fixing it, so I changed require_once('../private/mysqli_connect.php'); to require('../private/mysqli_connect.php');, and much to my surprise, it worked. Any ideas as to why that may be?

Thanks.

Dan Luba
  • 114
  • 2
  • 9

1 Answers1

0

When you use require_once PHP will check if the file has already been included, and if so, not include (require) it again. You can read it here.

So whats the problem here?
From your problem statement, I am assuming you have created another instance of this class before, or you have already included mysqli_connect.php somewhere else. And in your mysqli_connect.php you have created the connection link something like.

$dbc= mysqli_connect( ... );

So when you using require_once as the mysqli_connect.php is not loading again, your $dbc variable remain undefined. and your query does not work. But when you use require instead of require_once the file loaded again, and new connection created again, and your code works.

NB: Though changing to require, solved your problem, you should not use it like this. It will create new connection to your database, each time you create new instance of your class. For your thought: you can try creating something like this

Community
  • 1
  • 1
xiidea
  • 3,344
  • 20
  • 24
  • Thanks for your answer. So what should I do to fix it? – Dan Luba Apr 20 '14 at 02:05
  • 1
    As from your question I thought you need an explanation, what I gave. And for implementation it in a perfect way, you can follow any of well known patterns like : singletone factory pattern, registry pattern. An example singleton pattern link, I have already included in [here](http://stackoverflow.com/a/219599/1289495). – xiidea Apr 20 '14 at 02:10
  • Ah... so to fix it, I should learn how to program. Cool. Thanks for your help. :) – Dan Luba Apr 20 '14 at 02:12