Hi everybody
Could you please tell me,
how often do i need to connect mysql db in my php website??
i have created new mysql object but i worried about using it in top of pages or
in when i have to query something ??
help me please?
Hi everybody
Could you please tell me,
how often do i need to connect mysql db in my php website??
i have created new mysql object but i worried about using it in top of pages or
in when i have to query something ??
help me please?
Only once each time the page is loaded.
Every time a page is loaded (assuming you aren’t using a persistent connection), it’s like you are starting out fresh with your PHP, so everything is processed again, including the connection. Once you’re connected, you’re connected until that page is finished (or something extremely unusual happens).
Ideally, you would only create a connection when you need it. You could, create a function to only create a connection if/when you need it , something similar to:-
<?php
function getConnection(){
static $connection;
if(false === is_resource($connection)){
$connection = mysql_connect('localhost', 'user', 'pass');
if(false === is_resource($connection) || false === mysql_select_db('database')){
trigger_error(mysql_error(), E_USER_WARNING);
return false;
}
}
return $connection;
}
You can then include this function whenever you like, but it will only create a connection when called.
mysql_query('SELECT bacon FROM breakfast', getConnection());
Ok,thank you
but which is the best way for large website and large a mount of queries ?
More often that not, you’ll only ever really have one connection; regardless of the number of queries.
What Anthony was getting at is don’t create a connection if you aren’t going to use it on that particular page.
That function Anthony provided can be used anytime you need to run a query somewhere.
You would use it something like:
$conn = getConnection();
mysql_query("SELECT * FROM bob", $conn);
Since getConnection() uses a static variable, it’ll only ever create one connection (even if you call it multiple times).
The simpler, slightly less efficient but more traditional method is to just create a connection at the top of your script and use it throughout the rest of your page.
There are only a very few rare cases I can think of you might want more than one connection. 99.9% of the cases you’ll just need one connection.
One of those rare cases is an importer script moving data between databases while converting its structure.
Also, [fphp]PDO[/fphp] is a much better way to manage the connection than the old mysql library of functions.