At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple...

37
mysql_connect (PHP 4, PHP 5) mysql_connect — Open a connection to a MySQL Server Report a bug Description resource mysql_connect ([ string $server = ini_get("mysql.default_host") [, string $username = ini_get("mysql.default_user") [, string $password = ini_get("mysql.default_password") [, bool $new_link = false [, int $client_flags = 0 ]]]]] ) Opens or reuses a connection to a MySQL server. Report a bug Parameters server The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" for the localhost. If the PHP directive mysql.default_host is undefined (default), then the default value is 'localhost:3306'. In SQL safe mode, this parameter is ignored and value 'localhost:3306' is always used. username The username. Default value is defined by mysql.default_user. In SQL safe mode, this parameter is ignored and the name of the user that owns the server process is used.  password The password. Default value is defined by mysql.default_password. In SQL safe mode, this  parameter is ignored and empty password is used. new_link 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. The new_link  parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters. In SQL safe mode, this parameter is ignored. client_flags The client_flags parameter can be a combination of the following constants: 128 (enable LOAD DATA LOCAL handling), MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SP ACE or MYSQL_CLIENT_INTERACTIVE . Read the s ection about MySQL client constants for further information. In SQL safe mode, this parameter is ignored. Report a bug Return V alues Returns a MySQL link identifier on success or FALSE on failure. Report a bug Changelog Version Description 4.3.0 Added the client_flags parameter. 4.2.0 Added the new_link parameter.

Transcript of At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple...

Page 1: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 1/37

mysql_connect(PHP 4, PHP 5)

mysql_connect — Open a connection to a MySQL Server 

Report a bug Description

resource mysql_connect ([ string $server = ini_get("mysql.default_host") [, string $username =ini_get("mysql.default_user") [, string $password = ini_get("mysql.default_password") [, bool$new_link = false [, int $client_flags = 0 ]]]]] )Opens or reuses a connection to a MySQL server.

Report a bug Parameters

server The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a localsocket e.g. ":/path/to/socket" for the localhost.

If the PHP directive mysql.default_host is undefined (default), then the default value is'localhost:3306'. In SQL safe mode, this parameter is ignored and value 'localhost:3306' is alwaysused.

usernameThe username. Default value is defined by mysql.default_user. In SQL safe mode, this parameter isignored and the name of the user that owns the server process is used.

 passwordThe password. Default value is defined by mysql.default_password. In SQL safe mode, this

 parameter is ignored and empty password is used.

new_link If a second call is made to mysql_connect() with the same arguments, no new link will beestablished, but instead, the link identifier of the already opened link will be returned. The new_link 

 parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters. In SQL safe mode, this parameter isignored.

client_flagsThe client_flags parameter can be a combination of the following constants: 128 (enable LOAD

DATA LOCAL handling), MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS,MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE. Read the sectionabout MySQL client constants for further information. In SQL safe mode, this parameter is ignored.

Report a bug Return ValuesReturns a MySQL link identifier on success or FALSE on failure.

Report a bug ChangelogVersion Description4.3.0 Added the client_flags parameter.

4.2.0 Added the new_link parameter.

Page 2: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 2/37

Report a bug Examples

Example #1 mysql_connect() example

<?php$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');

if (!$link) {die('Could not connect: ' . mysql_error());

}echo 'Connected successfully';mysql_close($link);?>

Example #2 mysql_connect() example using hostname:port syntax

<?php

// we connect to example.com and port 3307$link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password');if (!$link) {

die('Could not connect: ' . mysql_error());}echo 'Connected successfully';mysql_close($link);

// we connect to localhost at port 3307$link = mysql_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password');if (!$link) {

die('Could not connect: ' . mysql_error());}echo 'Connected successfully';mysql_close($link);?>

Example #3 mysql_connect() example using ":/path/to/socket" syntax

<?php

// we connect to localhost and socket e.g. /tmp/mysql.sock 

//variant 1: ommit localhost$link = mysql_connect(':/tmp/mysql', 'mysql_user', 'mysql_password');if (!$link) {

die('Could not connect: ' . mysql_error());}echo 'Connected successfully';mysql_close($link);

// variant 2: with localhost$link = mysql_connect('localhost:/tmp/mysql.sock', 'mysql_user', 'mysql_password');if (!$link) {

Page 3: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 3/37

die('Could not connect: ' . mysql_error());}echo 'Connected successfully';mysql_close($link);?>

Report a bug Notes Note: Whenever you specify "localhost" or "localhost:port" as server, the MySQL client library willoverride this and try to connect to a local socket (named pipe on Windows). If you want to use TCP/IP, use "127.0.0.1" instead of "localhost". If the MySQL client library tries to connect to the wronglocal socket, you should set the correct path as in your PHP configuration and leave the server field

 blank.

 Note: The link to the server will be closed as soon as the execution of the script ends, unless it'sclosed earlier by explicitly calling mysql_close().

 Note: You can suppress the error message on failure by prepending a @ to the function name.

 Note: Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configuredirective doesn't contain character E. On Windows, if the environment is not copied theSYSTEMROOT environment variable won't be available and PHP will have problems loadingWinsock.

Report a bug See Also

mysql_pconnect() - Open a persistent connection to a MySQL server mysql_close() - Close MySQL connection

mysql_create_db mysql_close--------------------------------------------------------------------------------Last updated: Fri, 04 Jun 2010

add a note User Contributed Notesmysql_connecttpl99 at yandex dot ru30-Apr-2010 08:56Whenever you open two connections to a single database,you are likely not to get any error when selecting not existing db.

<?php$db1 = mysql_connect( ... );mysql_select_db('existing_db',$db1);

$db2 = mysql_connect( ... );mysql_select_db('not_existing_db', $db2);

Page 4: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 4/37

mysql_query(... , $db2);//will return no errors and the query wouldn't be executed.?>

Pay attention and you may save few hours of debugging.

chris at chriswpage dot com28-Mar-2010 09:01TA point to especially note from the above documentation is that the mysql client library has special

 behavior around "localhost", in that it will use a socket file instead of TCP/IP. Socket files, whilefaster, only work if the php script is on the same machine as the database.

I found this difficult to overcome when I split off a database server from a server that had a handfulof hosted clients all referencing "localhost". After significant effort, and failing with my knowledgeof socat and autossh tunnelling as mentioned as a workaround to setup a forward from the socketfile to TCP/IP in a mysql forum. I finally resorted to using DNS to reference the DB and no longer 

 provide "localhost". It was a pain to update clients, but live and learn.

I tend to work in distributed environments, and now make it a sort of rule of thumb/best practice touse DNS instead of hard coding "localhost" or "x.x.x.x".

Hope this helps others out there.

Chris Pageabelcheung at gmail dot com17-Mar-2010 06:37

 Note that named pipe on Windows is unusable since PHP 5.3, and TCP connection shall be usedeven in localhost.sholland at napervillegi dot com03-Dec-2009 05:18If you are getting an error "Can't assign requested address" you may have a problem with the mysql

 port. I had just moved my server to Mac OS X 10.6 and mysql_connect was giving this error.Going into the /etc/php.ini file and setting the default port number to 3306 fixed the problem.

mysql.default_port = 3306

The php.ini file suggests that PHP will select the port by using the $MYSQL_TCP_PORT or themysql-tcp entry in /etc/services, but in this case it is not so. /etc/services on my machine has 3306

listed, but it didn't get picked up.

This is sort of a bug report, in that the documented feature isn't working. Please don't delete thisuntil the community decides how to address the problem. This is one of those hair pulling exercisesto get fixed.Bruce Kirkpatrick 28-Oct-2009 05:48On Windows Vista or above, an entry in the Windows/System32/drivers/etc/hosts file causesmysql_connect() connections to "localhost" to timeout and never connect. This happens on php 5.3and above since it now uses mysql native driver which has changed it connection behavior compared to libmysql.dll in previous versions. It is not a PHP bug, but definitely a configuration

issue for users on new windows systems.

To get around this, you must remove the entry like this:

Page 5: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 5/37

::1 localhost

and make sure you still have:127.0.0.1 localhost

Also, you could change the code to connect to the ip instead, but that is inconvenient if you have

many web sites.

This issue occurs on Windows Vista, Windows 7 and Windows Server 2008.david dot schueler at wapkamera dot de11-Sep-2009 03:51If you are getting MySQL Errors like #2006: MySQL server has gone away, and you are usingmysql_connect() and pcntl_fork() then make shure that you are reconnecting to the mysql server with each created child which you fork()ed.

I pulled my hair out for many days because i was using the same mysql connection for each childand was getting that "MySQL server has gone away" errors.

Here is a simple example:<?php$link = mysql_connect($db_server, $db_user, $db_pass);mysql_select_db($db_database,$link));

$pid = pcntl_fork();if ($pid == -1)

// Error forking childelseif ($pid) {

// Parent will be here} else {

// The child has to esablish a *new* mysql connection.// if you use mysql_connect without the 4th parameter // then it will use the connection from the parent. But// if the child dies, the connection will be unaviable in// the parent too.// So, note the "true" as 4th parameter.$newlink = mysql_connect($db_server, $db_user, $db_pass,true);mysql_select_db($db_database,$newlink));// ...

}?>sedativchunk at gmail dot com31-Jul-2009 04:36Here is a connection class I created for one of my websites for a MYSQL connection. Feel free touse it on one of your applications anyone! It's MYSQL with OOP in mind and works similar toASP.net methods for connecting to a database. The benefit of this class is easy management of multiple MYSQL connections.

The class:

<?phpclass Connection

{

Page 6: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 6/37

var $db_connection = null; // Database connection stringvar $db_server = null; // Database server var $db_database = null; // The database being connected tovar $db_username = null; // The database usernamevar $db_password = null; // The database passwordvar $CONNECTED = false; // Determines if connection is established

/** NewConnection Method* This method establishes a new connection to the database. */

public function NewConnection($server, $database, $username, $password){

// Assign variablesglobal $db_connection, $db_server, $db_database, $db_username, $db_password;$db_server = $server;$db_database = $database;$db_username = $username;$db_password = $password;

// Attempt connectiontry{

// Create connection to MYSQL database// Fourth true parameter will allow for multiple connections to be made$db_connection = mysql_connect ($server, $username, $password, true);mysql_select_db ($database);if (!$db_connection){

throw new Exception('MySQL Connection Database Error: ' . mysql_error());}else{

$CONNECTED = true;}

}catch (Exception $e){

echo $e->getMessage();}

}

/** Open Method* This method opens the database connection (only call if closed!) */public function Open(){

global $db_connection, $db_server, $db_database, $db_username, $db_password,$CONNECTED;

if (!$CONNECTED){

try

{$db_connection = mysql_connect ($db_server, $db_username, $db_password);mysql_select_db ($db_database);

Page 7: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 7/37

if (!$db_connection){

throw new Exception('MySQL Connection Database Error: ' . mysql_error());}else{

$CONNECTED = true;}

}catch (Exception $e){

echo $e->GetMessage();}

}else{

return "Error: No connection has been established to the database. Cannot open

connection.";}

}

/** Close Method* This method closes the connection to the MySQL Database */public function Close(){

global $db_connection, $CONNECTED;if ($CONNECTED){

mysql_close($db_connection);$CONNECTED = false;

}else{

return "Error: No connection has been established to the database. Cannot closeconnection.";

}}

}?>cory dot mawhorter gmail.com02-Jul-2009 11:38Hopefully this saves someone some grief.

My dev computer is windows and runs wampserver. I have frequent problems with PHP beingunable to connect to MySQL after periods of extreme DB activity.

Long story short, it was because I was not running mysql via named-pipes and Windows wasrunning out of available ports to serve PHP. Apparently, on windows, you have 5000 ports to work 

with and once they are opened, they remain so for 120 seconds before being released. This causes problems with mysql/networking because a new port is requested for each connection.

Page 8: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 8/37

You can read more about the problem at:(Link too long and had to be broken up)http://dev.mysql.com/doc/refman/5.0/en/can-not-connect-to-server.html#can-not-connect-to-server-on-windows?>

Since mysql is on localhost, I can just enable named-pipes (which is how you should have mysqlsetup if you don't need networking) to get around the problem instead of the workaround listed onthat page.

For details, see:http://dev.mysql.com/tech-resources/articles/securing_mysql_windows.htmlContact at LinuxIntro dot com28-Oct-2008 05:34When you connect and expect to use a stored procedure,you must pass a special flag to MySQL viathe connect command, otherwise you will not get the results returned, and it will result in this error:

PROCEDURE AlexGrim.GetStats_ForumCategories can't return a result set in the given context

To fix this, change you connection string, adding ",false,65536" as the last 2 fields:$this->con = mysql_connect($this->h,$this->u,$this->p,false,65536);

 bmagilavy at avalon-internet dot com04-Sep-2008 08:00If you trying to connect to a remote server, here are a few things that can go wrong. Perhaps this listwill save someone some time:

1. You may need to get in touch with the remote server's tech support:

a. to ensure that you can get through its firewall. It is not necessarily enough to have your server number listed in the recipient site's cpanel remote access host list. It depends on how the server company has things set up;

b. to find out what port number they are using for database connections, which may not be thedefault used by mysql_connect;

c. If you are using ODBC, the host to which you are trying to connect may or may not have anyODBC drivers installed; and

d. If you are working from a dynamic IP, they may be set up to accommodate it, or you may haveto use a proxy. See http://forge.mysql.com/wiki/MySQL_Proxy .

2. If you are working from a shared server yourself, the server number you were sent in the sign-upletter is probably NOT the server number you should be using to connect to a remote database. Youneed the server number of the machine on which your site is sitting, not your virtual account server number on that machine. You can get this from your own tech support.

I am grateful to Jonathan Jones at Bluehost for this analysis. pascalxusNOSPAM at yahoo dot com22-Aug-2008 07:08

I just wanted to share a common wrapper that I use for executing one line SQL statements. Its aneasy wrapper to use that takes care of the connection open/close. Optionally, the mysql_connectcan be replaced with mysql_pconnect for persistent connections.

Page 9: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 9/37

function executeQuery( $query, $db, $nocon ){

if( $nocon != "nocon" )if( $db != "" ) connect( $db );else connect( "pascal_crm" );

$result= mysql_query( $query );$err = mysql_error();if( $err != "" ) echo "error=$err ";

if( $nocon != "nocon" )mysql_close();

return $result;}

Here's a related mysql_pconnect trivia question:

http://www.codesplunk.com/nr/questions/php17.htmlBoris K 25-Jul-2008 03:41Coderlit and angelo,

this may be the solution:

<?phpif (!isset($g_link)) {

$g_link = false;}

function GetMyConnection(){

global $g_link;if( $g_link )

return $g_link;$g_link = mysql_connect( 'localhost', 'dbuser', 'dbpass') or die('Could not connect to mysql

server.' );mysql_select_db('wordpress', $g_link) or die('Could not select database.');return $g_link;

}

function CleanUpDB(){

global $g_link;if( $g_link != false )

mysql_close($g_link);$g_link = false;

}

?>

coderlit at G dot mail\ dot com08-Jun-2008 03:56The note from angelo [at] mandato <dot> com is a good way to reuse the msyql connection, like

Page 10: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 10/37

mysql connection pooling.

However, you need to remove the $g_link = false; in the file. Other wise, everytime you includethis file, the mysql connection is set to false, and you have to call the mysql_connect again toconnect to the sql server, even though you may have already have live mysql connection ready for use.

<?php//need to remove this line to resue the connection resource

$g_link = false;

function GetMyConnection(){

global $g_link;if( $g_link )

return $g_link;$g_link = mysql_connect( 'localhost', 'dbuser', 'dbpass') or die('Could not connect to mysql

server.' );mysql_select_db('wordpress', $g_link) or die('Could not select database.');return $g_link;

}

function CleanUpDB(){

global $g_link;if( $g_link != false )

mysql_close($g_link);$g_link = false;

}

?>arithmetric at gmail dot com25-Mar-2008 06:59If you are trying to open multiple, separate MySQL connections with the same MySQL user,

 password, and hostname, you must set $new_link = TRUE to prevent mysql_connect from using anexisting connection.

For example, you are opening two separate connections to two different databases (but on the same

host, and with the same user and password):

$db1 = mysql_connect($dbhost, $dbuser, $dbpass);$rv = mysql_select_db($dbname1, $db1);$db2 = mysql_connect($dbhost, $dbuser, $dbpass);$rv = mysql_select_db($dbname2, $db2);

At this point, both $db1 and $db2 will have selected the database named by $dbname2.

The workaround is to require that the second MySQL connection is new:

$db1 = mysql_connect($dbhost, $dbuser, $dbpass);$rv = mysql_select_db($dbname1, $db1);$db2 = mysql_connect($dbhost, $dbuser, $dbpass, TRUE);

Page 11: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 11/37

$rv = mysql_select_db($dbname2, $db2);

 Now, $db1 should have selected $dbname1, and $db2 should have selected $dbname2.

This has been documented on the mysql_select_db page as well.

 Note: This occurs only when the server, username, and password parameters are identical for eachmysql_connect statement.aeolianmeson at blitzeclipse dot com03-Mar-2008 08:15Recently, I saw an obscure problem where I could connect to MySQL from the PHP via Apache andMySQL via the MySQL console, and could not connect via the PHP-CLI. This was in Windows(XP). I usually use MySQLi extension, but also tried MySQL, and both refused to work.

I restarted the service multiple times, and the PHP-CLI still would not connect.

This eventually cleared up.

I made sure to stop the service. Then, I downloaded a zipped binary-package from dev.mysql.comand started the server a few times from the commandline (mysqld/mysqld-nt, where mysqld-nt istuned specifically for Windows) and stopped it ("mysqladmin shutdown"). I was then able tosuccessfully connect from the PHP-CLI ("php -r "mysql_connect('localhost', 'root', ''); ").

Making sure it was stopped, I started the regular server from the commandline, and that was thensuccessful. I then stopped it and started it via the Services panel, and everything still worked.

I'm assuming that when the service was restarted initially, there was a component that had died andrefused to be shutdown even though the service appeared to be stopped, but shutting it down viamysqladmin killed everything entirely.dan at novapulsar dot com11-Feb-2008 07:24[EDIT by danbrown AT php DOT net: The issue this user is illustrating is a common problem whendealing with multiple databases from PHP. Note his comments at the end of the code for anexplanation.]

Looks like I learned this the hard way:

<?php

//establish connection to master db server mysql_connect (DB_HOST, DB_USER, DB_PASSWORD);mysql_select_db (DB_NAME);

//establish connection to read-only slave cluster $objMySQL_Read = mysql_connect (SLAVE_DB_HOST, SLAVE_DB_USER,SLAVE_DB_PASSWORD);mysql_select_db (DB_NAME, $objMySQL_Read);

$strSQL = "SELECT col1,col2 FROM " . DB_NAME . "." . "tbl1 WHERE 1=1";

$objRS = mysql_query ($strSQL, $objMySQL_Read); //returns data from slaves

Page 12: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 12/37

$strSQL = "INSERT INTO " . DB_NAME . "." . "tbl1 (col1,col2) VALUES (val1,val2)";

mysql_query ($strSQL);

//expected behavior, to insert the last statement into the master db, since it doesn't reference the

read-only resource explicitly. instead, it inserts the record into the last connection, even though itshouldn't, since the last connection is not a global/anonymous connection like the first one, it's$objMySQL_Read.

//you'll get out of sync db's across your cluster unless you explicitly define all connection resources

?>Steve24-Dec-2007 11:32The too many connections issue can be due to several problems.

1. you are using pconnect. This can tie up many connections and is not really needed for MySQL asnew connections are really fast.

2. Apache children are hanging around for too long - combine this with pconnect and you haverecipe for disaster.

Suggestions: reduce the amount of time apache child processes stay connected to the client and howmany connections before they are killed off. And don't use pconnect.Ignacio Casinelli Esviza20-Oct-2007 05:51Sometimes, I want that MySQL service start automatically when my app need it. This is speciallytrue if you work in a development PC and/or in an small intranet environment.

You can do something like this: if the mysql_connect() function returns FALSE, try to force theinitialization of the MySQL service!

For example, under Windows:

<?php

$link = @mysql_connect($server,$user,$pass);

if (empty($link)){@exec("%SystemRoot%\\system32\\net.exe start mysql");sleep(5);$link = @mysql_connect($servidor,$usuario,$clave);

}

?>

In Linux of course you can try "/etc/init.d/mysqld start" but you will need special permissions.

Regards.

Peter Robinett02-Oct-2007 01:20The use of mysql connections can become tricky with objects. I am using mysql_connect() in a

Page 13: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 13/37

Page 14: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 14/37

$link2 = mysql_connect("localhost");?>

so if you wanted to switch between connections just by call to mysql_connect, and rely on itsinternal link caching, you can be wasting your database connections.angelo [at] mandato <dot> com

19-Mar-2007 09:07The post from 'Graham_Rule at ed dot ac dot uk' should include the following WARNING:

WARING: THE VALUES OF THESE DIRECTIVES WILL BE EXPOSED IF ANY OF THECODE INCLUDES THE phpinfo() FUNCTION.

The phpinfo() function will print these values clear as day. I highly suggest against this method of storing MySQL authentication information.

I recommend creating connect and cleanup functions in a separate include file. If security is aconcern, locate the include file outside of your web root folder.

<?php$g_link = false;

 function GetMyConnection(){

global $g_link;if( $g_link )

return $g_link;$g_link = mysql_connect( 'host.name', 'user', 'password') or die('Could not connect to server.' );mysql_select_db('database_name', $g_link) or die('Could not select database.');return $g_link;

function CleanUpDB(){

global $g_link;if( $g_link != false )

mysql_close($g_link);$g_link = false;

}

 ?>

Simply include your connnection.php file in your script and anywhere you use the mysql_query()function include a call to the GetMyConnection() function.

<?php$res = mysql_query("SELECT ...", GetMyConnection() );

?>sky dot sama dot remove dot dots at Gmail dot com12-Dec-2006 04:42

In case anyone else is getting "Client does not support authentication protocol requested by server;consider upgrading MySQL client" error. The problem is the new password hashing method used byMySQL >= 4.1 mentioned below.

Page 15: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 15/37

Either update your PHP to v5 where the new password hashing is supported or use old_password()in MySQL 4.1.

FROM: http://www.digitalpeer.com/id/mysql

UPDATE mysql.user SET password=old_password("youroldhashpassword") WHERE user ='youruserid' and host ='yourhost'

then do

FLUSH PRIVILEGESGraham_Rule at ed dot ac dot uk 10-Nov-2006 09:59How to get at multiple MySQL databases from PHP while continuing to hide the user credentials inApache configuration files.

(This builds on my solution to the problem of hiding such credentials that I posted in May 2003 athttp://uk2.php.net/manual/en/function.mysql-connect.php#32035)

<Directory /var/www/html/multidatabase>php_value mysql.default_user "username1 username2"

  php_value mysql.default_password "secret private"php_value mysql.default_host "localhost server.example.com"

</Directory>

 Note that the quotes are necessary to prevent the parser complaining about seeing too many parameters for php_value.

Given this setup in Apache, our script can fetch the composite value$hostnames = @ini_get('mysql.default_host');

harjono

Page 16: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 16/37

Split it into its component parts$hostnames = preg_split("/[\s]+/", $hostnames);

Then use the values in this array as if we had hard-coded:$hostnames[0] = "localhost";$hostnames[1] = "server.example.com"

Similar code may be written to fetch the usernames and passwords.

(One 'gotcha' with the mysql_error() function is that it will not give a sensible error report if there isa failure to open a second or subsequent connection. It uses the last successfully opened connectionas the basis for its message!)Graham_Rule at ed dot ac dot uk 10-Nov-2006 09:43The addition of entries to httpd.conf to stop .inc files being served by Apache is certainly useful andto be recommended.

But it doesn't change the fact that these files have to be readable by Apache so that the PHP processor can get at them.

Page 17: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 17/37

As long as your don't have multiple, possibly untrusted, users on your machine then that's OK. Butwhen you are running a large multi-user service with thousands of users its always possible that oneof them will look at your .inc files and take a note of the passwords you have in them. They couldeven copy them into their own scripts and modify your databases!

Even if local users are trusted, there is always the possibility of a rogue script (PHP or some nastier 

language) being installed by an ignorant user. That script might then read your .inc files (whether or not they are in the web publishing tree) and expose your password.

 brinca at substancia dot com09-Nov-2006 03:43If you prefer to use a hostname instead of an ip on your connection string in a script (to be able tochange the ip at will), but don't want the overhead of dns lookups, just add it to your /etc/hosts file(in windows: %WINDIR%/system32/drivers/etc/hosts).

For example, add the following to your hosts file (changing the bogus ip to your server's real ip):

123.123.123.123 mysqlserver1

 Note: On linux, make sure you have "order: hosts,bind" on your /etc/host.conf file.

On a script, make the mysql connection like so:

<?$sid = mysql_connect ("mysqlserver1", "user", "pass");

?>

 Note: this sample is in php, but it can be any other programming language (just type "pingmysqlserver1" on a prompt, on your server)

And there you have it! If your server ever gets assigned a different ip, just update the hosts file withthe new one (every script will work as-is, even if under different hostnames).rui dot batista at netcabo dot pt31-May-2006 03:42Ever wonder what "default username" is?<?php$link = mysql_connect() or die(mysql_error());$result = mysql_query("SELECT SESSION_USER(), CURRENT_USER();");$row = mysql_fetch_row($result);

echo "SESSION USER: ", $row[0], "<br>\n";echo "CURRENT USER: ", $row[1], "<br>\n";?>Both are ODBC@localhost in my win2k install, so my advice for windows is:- create a MySQL user named ODBC with no password- add localhost to ODBC user [right-click ODBC]- set schema previleges to ODBC@localhost- use mysql_connect() with no parms, or do not use ;)This turns to work also with odbc_connect:odbc_connect("myDSN", "", "")Aesar 

09-May-2006 05:26That's an interesting discovery. I don't think it should be this way, but I think it's more afirefox/browser bug (at least, if you see it as a bug) than a fault in mysql/php.

Page 18: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 18/37

What happens if you load the pages in two different browser screens instead of two tabs?Mario08-May-2006 04:21PHP (5.1.2) stores connections according to script name and remote host, apparently. If the samescript is requested by the same browser in two different tabs (Firefox for this test) and requests a

non-persistent connection using the same user and password, the connection will be shared.

Ran into this while testing a script for concurrent usage using "LOCK TABLES" queries... andfound that one tab's script was blocking until the other finished. No blocking occurred whendifferent machines loaded the same script at the same time. Very interesting.25-Jun-2005 10:18connect to mysql via named pipe under windows :

in my.ini, add this:

[mysqld]

enable-named-pipe

then connect to the server, then connect to mysql using

mysql_connect('.')camitz at NOSPAM dot example dot com

hajono

Page 19: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 19/37

27-Oct-2004 08:05A description about the problem with the password hashing and how to adress them can be found athttp://dev.mysql.com/doc/mysql/en/Password_hashing.htmlchaoscontrol_hq at yahoo dot com23-Aug-2004 09:10In MySQL4.1 and later, the default password hashing format has changed making it incompatible

with 3.x clients.I found out mysql_connect() works on server versions >= 4.1 when your MySQL user password is

 blank because password authentication isn't done in that case, otherwise you need to use another connection method (e.g. mysqli).Also if you are using old MySQL tables on a new server (i.e. the passwords are stored in the oldformat), then the server will use the old auth method automatically and this function should work inall cases.Hopefully this will help someone, it had me confused for a while because some of the users on my4.1 server could connect and some couldn't.martinnitram at excite dot com31-Oct-2003 10:22to use load data local infile function from mysql (at mysql 4.0.16, php 4.3.3), set fifth parameter of mysql_connect() to CLIENT_LOCAL_FILES(128), which based on MYSQL C API ( also mysqlserver support load file, check by "show variables like 'local_infile' ")

Page 20: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 20/37

Thank 'phpweb at eden2 dot com' to point this out phpweb at eden2 dot com28-Jun-2003 06:55client_flags can be things other than MYSQL_CLIENT_COMPRESS,MYSQL_CLIENT_IGNORE_SPACE and MYSQL_CLIENT_INTERACTIVE.

I presume that mysql_connect() just passes through to the C MySQL API, which provides theseconstants:

#define CLIENT_LONG_PASSWORD 1 /* new more secure passwords */#define CLIENT_FOUND_ROWS 2 /* Found instead of affected rows */#define CLIENT_LONG_FLAG 4 /* Get all column flags */#define CLIENT_CONNECT_WITH_DB 8 /* One can specify db on connect */#define CLIENT_NO_SCHEMA 16 /* Don't allow database.table.column */#define CLIENT_COMPRESS 32 /* Can use compression protocol */#define CLIENT_ODBC 64 /* Odbc client */

#define CLIENT_LOCAL_FILES 128 /* Can use LOAD DATA LOCAL */#define CLIENT_IGNORE_SPACE 256 /* Ignore spaces before '(' */#define CLIENT_CHANGE_USER 512 /* Support the mysql_change_user() */#define CLIENT_INTERACTIVE 1024 /* This is an interactive client */#define CLIENT_SSL 2048 /* Switch to SSL after handshake */#define CLIENT_IGNORE_SIGPIPE 4096 /* IGNORE sigpipes */#define CLIENT_TRANSACTIONS 8192 /* Client knows about transactions */

 Not all of these may work or be meaningful, but CLIENT_FOUND_ROWS does, at least.Graham_Rule at ed dot ac dot uk 14-May-2003 03:43Another solution to the security problems of putting usernames and passwords into scripts. I haven'tfound this documented anywhere else so thought I'd suggest it for the online documentation. ........

Don't put passwords for mysql into scripts which may be read by any user on the machine. Instead put them into an Apache configuration file and make sure that it is not world-readable. (Apachereads its main config files as root.)

For example, add this to your httpd.conf (and chmod it to 600 or 660) then tell your apache toreload itself (apachectl graceful).

<Directory /var/www/html/mydatabase> php_value mysql.default_user fred php_value mysql.default_password secret php_value mysql.default_host server.example.com

</Directory>

Then all you need in your PHP code is

$handle = mysql_connect() or die(mysql_error());

The passwords etc will only be picked up by scripts running in the named directory (or a sub-

directory). The same may be done for virtualhosts etc.

If you don't want to keep reloading your Apache server then you ay test things putting the

Page 21: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 21/37

 php_value directives into a (world readable) .htaccess file. (Clearly not for production use.)

If you need to debug the values that are being supplied (or not) then use this snippet:

@syslog(LOG_DEBUG, "Using user=".ini_get("mysql.default_user")." pass=".ini_get("mysql.default_password").

" host=".ini_get("mysql.default_host"));

(This assumes that you are not running in 'safe_mode' and that you are on a unix of some sort.)amn -at- frognet.net12-Mar-2003 06:40Just in case you didn't know. You can use mysql_connect in a function to connect to a database andthe connection is a super-global... meaning you can use mysql_query in other functions or in nofunction at all and PHP will use the connection that you opened. This is a handy bit of knowledgethat helps if you have a large site with lots of scripts. If you create one function to connect to a db,and call that function in all your scripts, it makes for easier code maintenance since you only haveto update one line of code to change your mysql connection instead of updating all your scripts

individually.add a note

mysql_create_db mysql_close--------------------------------------------------------------------------------Last updated: Fri, 04 Jun 2010

havid

Page 22: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 22/37

widi

Page 23: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 23/37

Page 24: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 24/37

harjono

Page 25: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 25/37

havid

widi

Page 26: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 26/37

harjono

Page 27: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 27/37

1000000 years

Page 28: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 28/37

havid

widi

Page 29: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 29/37

harjono

havid

Page 30: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 30/37

widi

Page 31: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 31/37

Page 32: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 32/37

1000000 years

Page 33: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 33/37

she was very nice once I ever knew him very wellappreciate the friendly and polite

1000000 years

Page 34: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 34/37

Page 35: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 35/37

she was very nice once I ever knew him very wellappreciate the friendly and polite

Page 36: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 36/37

Page 37: At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases From PHP.

8/9/2019 At Php DOT Net the Issue This User is Illustrating is a Common Problem When Dealing With Multiple Databases Fro…

http://slidepdf.com/reader/full/at-php-dot-net-the-issue-this-user-is-illustrating-is-a-common-problem-when 37/37

she was very nice once I ever knew him very wellappreciate the friendly and polite