Page 1 of 1

is this bad practise?

Posted: Mon Jan 22, 2007 6:24 am
by konstandinos
hi i have some standard php functions, that pull data from a database and spit out formatted html.

so first i have the base script:

Code: Select all

<?php
     include("functions/foo.php");
     print_html_header();
     fubar($table);
     print_html_footer();     
?>
then the fubar() function, described below, initialises the mysql connection, queries the dbase for the data, and outputs the formatted html...

Code: Select all

// inside foo.php
...

     function fubar($table)
     {
           $connection_A = mysql_connect(...);

           //some code...

           another_function_call();

           mysql_close($connection_A);
     }
...
but then i have another function, another_function_call(), which also inits a sql connection to the same database...

Code: Select all

// further down in foo.php
...
     function another_function_call()
     {
          $connection_B = mysql_connect(...same database);
          
          //do stuff
     
          mysql_close($connection_B);
     }
...
what i am wondering is if this is bad? it's almost like a nested mysql connection, for use of a better description.

i personally don't see anything wrong with it. but then again, if ive already initialised a sql connection, should i try use the same one? or is there no danger in my current approach?

Posted: Mon Jan 22, 2007 6:35 am
by kaszu
From http://uk.php.net/mysql_connect
If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.
Personally i wouldn't call mysql_connect(...) once more in this case.

Posted: Mon Jan 22, 2007 6:37 am
by m3mn0n
Moving this to PHP Theory & Design.

Posted: Mon Jan 22, 2007 6:41 am
by konstandinos
kaszu wrote:...
Personally i wouldn't call mysql_connect(...) once more in this case.
yeah i guess you're right. i can just have mysql_query(...) inside of another_function_call() and it will use the current connection.

ok thanks for clearnig that up.

Posted: Mon Jan 22, 2007 9:05 am
by raghavan20
you can normally have a database manager to handle database connections.
you can use singleton design pattern to reuse database connections.
but do not the same connection if you are handling transactions.
you can same connection for simple searches and normal retrieval of data from DB but do not use connection if you are dealing with creating orders and processing payments.

if you do not want to handle complex OO practices, you can still pass the same DB connection to various functions that are called in a page but it would get messy when the application grows large.