suche nach in der

mysql_create_db> <mysql_close
Last updated: Fri, 18 May 2012

view this page in

mysql_connect

(PHP 4, PHP 5)

mysql_connectÖffnet eine Verbindung zu einem MySQL-Server

Beschreibung

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 ]]]]] )

Öffnet eine neue Verbindung (oder nutzt bestehende) zu einem mySQL Server.

Parameter-Liste

server

Der MySQL Server. Er kann zudem eine Portnummer enthalten, z.B. "hostname:port" oder den Pfad zu einem lokalen Socket z.B. ":/pfad/zum/socket" für Zugriffe auf dem lokalen Rechner (localhost).

Wenn die PHP Direktive mysql.default_host nicht definiert ist (Standard), ist der Vorgabewert 'localhost:3306'. Bei SQL safe mode wird dieser Paramter ignoriert und der Wert 'localhost:3306' immer genutzt.

username

Der Nutzername. Der Standardwert ist durch mysql.default_user definiert. Bei SQL safe mode wird dieser Parameter ignoriert und der Name des Nutzers, dem der Prozess gehört, genutzt.

password

Dass Passwort. Der Standardwert ist durch mysql.default_password definiert. Bei SQL safe mode wird dieser Parameter ignoriert und ein leeres Passwort genutzt.

new_link

Für den Fall, dass ein zweiter Aufruf von mysql_connect() mit den gleichen Argumenten erfolgt, wird keine neue Verbindung aufgebaut, sondern die Verbindungs-Kennung der schon bestehenden Verbindung zurückgeliefert. Der Parameter new_link beeinflusst dieses Verhalten und mysql_connect() öffnet immer eine neue Verbindung, sogar dann, wenn mysql_connect() zu einem früheren Zeitpunkt mit den gleichen Parametern aufgerufen wurde. Bei SQL safe mode wird dieser Parametern ignoriert.

client_flags

Der Parameter client_flags kann eine Kombination der folgenden Konstanten sein: 128 (erlaube LOAD DATA LOCAL Nutzung), MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE oder MYSQL_CLIENT_INTERACTIVE. Lesen sie den Abschnitt über MySQL-Client Konstanten für weitergehende Informationen. Bei SQL safe mode wird dieser Parameter ignoriert.

Rückgabewerte

Gibt eine MySQL Verbindungs-Kennung im Erfolgsfall zurück oder Im Fehlerfall wird FALSE zurückgegeben..

Changelog

Version Beschreibung
4.3.0 Der client_flags Parameter wurde hinzugefügt.
4.2.0 Der new_link Parameter wurde hinzugefügt.

Beispiele

Beispiel #1 mysql_connect() Beispiel

<?php
$link 
mysql_connect('localhost''mysql_user''mysql_password');
if (!
$link) {
    die(
'Verbindung schlug fehl: ' mysql_error());
}
echo 
'Erfolgreich verbunden';
mysql_close($link);
?>

Beispiel #2 mysql_connect() Beispiel unter Nutzung der hostname:port Syntax

<?php
// Verbing zu example.com auf Port 3307
$link mysql_connect('example.com:3307''mysql_user''mysql_password');
if (!
$link) {
    die(
'Verbindung schlug fehl: ' mysql_error());
}
echo 
'Erfolgreich verbunden';
mysql_close($link);

// Verbindung zu localhost auf port 3307
$link mysql_connect('127.0.0.1:3307''mysql_user''mysql_password');
if (!
$link) {
    die(
'Verbindung schlug fehl: ' mysql_error());
}
echo 
'Erfolgreich verbunden';
mysql_close($link);
?>

Beispiel #3 mysql_connect() Beispiel unter Nutzung der ":/path/to/socket" Syntax

<?php
// Verbing zu localhost und Socket z.B. /tmp/mysql.sock

// Variante 1: localhost weglassen
$link mysql_connect(':/tmp/mysql''mysql_user''mysql_password');
if (!
$link) {
    die(
'Verbindung schlug fehl: ' mysql_error());
}
echo 
'Erfolgreich verbunden';
mysql_close($link);


// Variante 2: mit localhost
$link mysql_connect('localhost:/tmp/mysql.sock''mysql_user''mysql_password');
if (!
$link) {
    die(
'Verbindung schlug fehl: ' mysql_error());
}
echo 
'Erfolgreich verbunden';
mysql_close($link);
?>

Anmerkungen

Hinweis:

Immer wenn sie "localhost" oder "localhost:port" als Server angeben, wird die MySQL Client Bibliothek dies überschreiben und versuchen, sich zu einem lokalen Socket (named pipe unter Windows) zu verbinden. Wenn sie TCP/IP nutzen möchten, nutzen sie "127.0.0.1" anstatt "localhost". Wenn die MySQL Client Bibliothek versucht, sich zu dem falschen lokalen Socket zu verbunden, sollten sie den korrekten Pfad als in ihrer PHP Konfiguration setzen und das Server Feld leer lassen.

Hinweis:

Die Verbindung zum Server wird, sobald die Ausführung des Skripts endet, geschlossen, außer sie wurde zuvor exlizit durch den Aufruf von mysql_close() geschlossen.

Hinweis:

Sie können die Fehlermeldungen bei Fehlern durch Voranstellen von einem @ an den Funktions Namen unterdrücken.

Hinweis:

Error "Can't create TCP/IP socket (10106)" deutet meist daruf hin, dass die variables_order Konfigurations Anweisung nicht das E Zeichen enthält. Wird unter Windows die Umgebung nicht kopiert, ist die SYSTEMROOT Umgebungs Variable nicht verfügbar und PHP wird Sccwierigkeiten haben, Winsock zu laden.

Siehe auch



add a note add a note User Contributed Notes
mysql_connect
michael at golightly dot com
11-Apr-2007 05:16
Drowning under a sea of connections using mysql_connect (not pconnect) I found that php connections did NOT go away at the end of a page load.  Only by setting the directive mysql.allow_persistent = Off made the connections go away.  So unless I've missed something else or don't understand the meaning of 'script' the following note on this page is incorrect:

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

Using PHP 4.4.4 & MySQL 4.0.26
jslakva at gmail dot com
08-Apr-2007 03:05
if between first and second call with same arguments there was another call with another argument, initial connection link is not reused, but new connection is created instead, regardless of new_link argument.

for example, here only one single link will be opened and then reused:
<?php
$link1
= mysql_connect("localhost");
$link2 = mysql_connect("localhost");
?>

and here _three_ separate links will be opened:
<?php
$link1
= mysql_connect("localhost");
$link3 = mysql_connect("127.0.0.1");
$link2 = mysql_connect("localhost");
?>

so if you wanted to switch between connections just by call to mysql_connect, and rely on its internal link caching, you can be wasting your database connections.
angelo [at] mandato <dot> com
19-Mar-2007 10:07
The 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 THE CODE 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 a concern, 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 com
12-Dec-2006 05: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 by MySQL >= 4.1 mentioned below.

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 PRIVILEGES
Graham_Rule at ed dot ac dot uk
10-Nov-2006 10:59
How to get at multiple MySQL databases from PHP while continuing to hide the user credentials in Apache configuration files.

(This builds on my solution to the problem of hiding such credentials that I posted in May 2003 at http://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');                                                                                                           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 is a failure to open a second or subsequent connection.  It uses the last successfully opened connection as the basis for its message!)
Graham_Rule at ed dot ac dot uk
10-Nov-2006 10:43
The addition of entries to httpd.conf to stop .inc files being served by Apache is certainly useful and to 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.

As long as your don't have multiple, possibly untrusted, users on your machine then that's OK.  But when you are running a large multi-user service with thousands of users its always possible that one of them will look at your .inc files and take a note of the passwords you have in them.  They could even 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 com
09-Nov-2006 04:43
If you prefer to use a hostname instead of an ip on your connection string in a script (to be able to change 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 "ping mysqlserver1" 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 with the new one (every script will work as-is, even if under different hostnames).
rui dot batista at netcabo dot pt
31-May-2006 05:42
Ever 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 07:26
That's an interesting discovery. I don't think it should be this way, but I think it's more a firefox/browser bug (at least, if you see it as a bug) than a fault in mysql/php.

What happens if you load the pages in two different browser screens instead of two tabs?
Mario
08-May-2006 06:21
PHP (5.1.2) stores connections according to script name and remote host, apparently. If the same script 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... and found that one tab's script was blocking until the other finished. No blocking occurred when different machines loaded the same script at the same time. Very interesting.
25-Jun-2005 12:18
connect 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
27-Oct-2004 10:05
A description about the problem with the password hashing and how to adress them can be found at http://dev.mysql.com/doc/mysql/en/Password_hashing.html
chaoscontrol_hq at yahoo dot com
23-Aug-2004 11:10
In 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 old format), then the server will use the old auth method automatically and this function should work in all cases.
Hopefully this will help someone, it had me confused for a while because some of the users on my 4.1 server could connect and some couldn't.
martinnitram at excite dot com
31-Oct-2003 11:22
to 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 mysql server support load file, check by "show variables like 'local_infile' ")

Thank  'phpweb at eden2 dot com' to point this out
phpweb at eden2 dot com
28-Jun-2003 08:55
client_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 these constants:

#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 05:43
Another solution to the security problems of putting usernames and passwords into scripts. I haven't found 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. (Apache reads 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 to reload 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 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.net
12-Mar-2003 07:40
Just in case you didn't know. You can use mysql_connect in a function to connect to a database and the connection is a super-global... meaning you can use mysql_query in other functions or in no function at all and PHP will use the connection that you opened. This is a handy bit of knowledge that 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 have to update one line of code to change your mysql connection instead of updating all your scripts individually.
rec0rder at lycos dot com
09-Apr-2002 08:54
The method I use to "protect" mySQL connect is to place dbConnect.php outside the web directory.

I will create a directory:
/var/include/

Put "dbConnect.php" into
/var/include/

Edit your php.ini file to read "/var/include/" an include directory.

In your PHP now, you just have to do:
require("dbConnect.php");
nospam at code24 dot com
27-Mar-2002 12:37
There should already be a post in here about this, but I would like to follow up on the idea that anyone can read your .inc files, which might contain username/password combos for mysql access.

There is a very simple way to block this.

If you are using Apache, just edit your httpd.conf file, and look for the following lines:

<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy All
</Files>

Okay... that little chunk of text is saying that you don't want files that begin with .ht to be readable through apache. We also don't want people to see any files that end with .inc.

So, just add the following chunk of text to your httpd.conf file:

<Files ~ "\.inc(\.php)?$>
    Order allow,deny
    Deny from all
    Satisfy All
</Files>

This will block anyone from seeing your .inc files over the web.  It is much smarter than naming include files, "*.php".  Use the .php extension for your code, and save .inc for actual include data, and don't worry about people reading your .inc's anymore.

Hope this helps somebody.  Oh yeah... one other thing... obviously, anytime you make a change to httpd.conf (or whatever you have named your Apache config file), you must restart apache for the changes to take effect.

mysql_create_db> <mysql_close
Last updated: Fri, 18 May 2012