How do you efficiently connect to mysql in php without reconnecting on every query -


I want to rewrite my code every time when I learn something new about PHP (such as mysql connection Can not be passed around in a session as a handle).

How do you apply mysql connections to your projects? A lot of people have proposed "connection pooling", but I've still lost my manual after reading the manual. Looks like: "Connection pooling is mysql_pconnect!" - Me: "And ...? How is this a difference in reality? Can you pass a mysql_pconnect in a session? It seems that why is the mysterious aura ??"

Let me explain your situation. I have a function called "query1":

  function query1 ($ query) {$ db = new mysql (HOST, USER, PASS, DBNAME); $ Result = $ db- & gt; Query ($ query); $ Db- & gt; near (); Return result; }  

This is a difficult and inefficient way to interrogate DB ( especially since you need mysql handles for functions like mysql_real_escape_string) is. What is the right form to do this? Can somebody help me out?

Thank you, I really appreciate a good honest answer.

Normally the connection page loads once. AKA

  class database {connect public function () {$ this- & gt; Connection = mysql_connect (); } // It will be called at the end of the script Public Function __destruct () {mysql_close ($ this-> Connection); } Public function function query ($ query) {mysql_query Return ($ query, $ this-> connection); }} $ Database = new database; $ Database- & gt; Connect (); $ Database- & gt; Query ("INSERT IN TABLE (` name`) VALUES ('uncle') ");  

Actually, you open the connection at the beginning of the page, close it on the end page. After that, you can do various questions during the page and there is no need to do anything in connection.

Eric As Suggestion you can also mysql_connect in the constructor.


To use the above global variable (this creates a global status, is not a suggestion), you do something like

  global $ Db; $ Db = new database; // ... startup stuff function doSomething () {global $ db; $ Db- & gt; Query ("Do something"); }  

Oh, and no one has told that you do not have to pass around the parameter just connect

  mysql_connect () ;  

After that, mysql_query will only use the last connection, no matter what the scope is.

  mysql_connect (); Function doSomething () {mysql_query ("do something"); }  

To the comments:

I think you should use mysql_pconnect () instead of mysql_connect (), because mysql_connect ( ) Does not use connection pooling - night code

Would you like to consider whether you use mysql_connect or mysql_pconnect We do. However, you still only need to connect once per script.


Comments

Popular posts from this blog

oracle - The fastest way to check if some records in a database table? -

php - multilevel menu with multilevel array -

jQuery UI: Datepicker month format -