mysql_connect()
mysql_connect(server[:port|socket], user, password[,new_link,flags])
Use this function to start a MySQL connection. The first
argument of the function is the server name. If none is specified,
localhost is assumed. A port may be specified
with the server name (separated by a colon) or a socket along with its
path. If no port is given, port 3306 is assumed. The username is to be
given as the second argument and the user’s password as the third. If
a connection is attempted that uses the same parameters as a previous
one, the existing connection will be used and a new connection link
will not be created unless new_link is
specified as the fourth argument of this function. As an optional
fifth argument, client flags may be given for the MySQL constants
MYSQL_CLIENT_COMPRESS,
MYSQL_CLIENT_IGNORE_SPACE,
MYSQL_CLIENT_INTERACTIVE, and
MYSQL_CLIENT_SSL. The function returns a connection
identifier if successful; it returns false if it’s unsuccessful. Use
mysql_close() to close a connection created
by mysql_connect(). Here is an
example:
#!/usr/bin/php -q
<?
mysql_connect('localhost', 'ricky', 'adams');
mysql_select_db('workrequests');
...To be able to identify the connection link later, especially
when a script will be using more than one link, capture the results of
mysql_connect(). Here is a complete script
that sets up two connections to MySQL and captures the resource
identification number for each link:
#!/usr/bin/php -q
<?
$user1 = 'elvis';
$user2 = 'fats';
$connection1 = mysql_connect('localhost', $user1, 'ganslmeier123');
$connection2 = mysql_connect('localhost', $user2, 'holzolling456');
mysql_select_db('workrequests', $connection1);
mysql_select_db('workrequests', $connection2);
counter($connection1,$user1);
counter($connection2,$user2);
function counter($connection,$user) {
$sql_stmnt = "SELECT * FROM workreq";
$results = mysql_query($sql_stmnt, $connection);
if(mysql_errno($connection)){
print "Could not SELECT with $connection for $user. \n";
return;
}
$count = mysql_num_rows($results);
print "Number of Rows Found with $connection for $user:
$count. \n";
}
mysql_close($connection1);
mysql_close($connection2);
?>In this example, two links are established with different
usernames. The counter() subroutine is called
twice, once with each connection identifier and username passed to the
user-defined function. For the first connection, the user
elvis does not have SELECT
privileges, so the SQL statement is unsuccessful. An error is
generated and the number of rows is not determined due to the
return ending the function call. For the second
connection, the user fats has the necessary
privileges, so the function is completed successfully. Here is the
output from running this script on my server:
Could not SELECT with Resource id #1 for elvis. Number of Rows Found with Resource id #2 for fats: 528.