I have a PHP page index.php
. In this page, I am creating a connection with a MySQL database (using mysqli
), and executing some MySQL queries. I am opening the connection ($connection = new mysqli("localhost", "root", "");
) in the start of index.php
file, and closing the connection ($connection->close()
) at the end of the index.php
file.
Within the HTML <head>
portion of index.php
, I have included a JQuery script which makes an AJAX call to another PHP file load_more_data.php
, which makes a few MySQL SELECT
queries. This JQuery script is invoked on the click of button.
What I am currently doing is that in load_more_data.php
file, I open a NEW connection with the same database (by calling $connection = new mysqli("localhost", "root", "");
) and then execute the queries. But there is a problem: When I execute my queries by doing $connection->query($sql)
from index.php
, the run fine and the correct dataset is returned. BUT when I execute the same query from load_more_data.php
, $connection->query($sql)
returns FALSE
.
QUESTIONS:
I have two questions:
Is this the right approach? That is creating a new connection object in each file which needs to query the database? or is there a way to pass one connection object from server side (
index.php
) to client side (JQuery script) from where AJAX sends that connection object back to the server side (load_more_data.php
)? How should I go about this thing?Why is
$connection->query($sql)
returning FALSE when called fromload_more_data.php
, when it returns the proper expected dataset fetched from database when called fromindex.php
?