mysql_connect

(PHP 3, PHP 4, PHP 5)

mysql_connect -- Открывает соединение с сервером MySQL

Описание

resource mysql_connect ( [string server [, string username [, string password [, bool new_link [, int client_flags]]]]] )

Возвращает указатель на соединение с MySQL в случае успешного выполнения, или FALSE при неудаче.

mysql_connect() устанавливает соединение с сервером MySQL. Следующие значения по умолчанию установлены для отсутствующих параметров: server = 'localhost:3306', username = имя пользователя владельца процесса сервера и password = пустой пароль.

Параметр server может также включать номер порта, к примеру "hostname:port" или путь к сокету, к примеру ":/path/to/socket" для локального сервера.

Замечание: При указании параметру server значения "localhost" или "localhost:port" клиентская библиотека MySQL будет пытаться соединиться с локальным сокетом. Если вы всё же хотите использовать TCP/IP, используйте адрес "127.0.0.1" вместо "localhost". Если клиентская библиотека пытается подключиться не к тому локальному сокету, это можно исправить через указание директивы mysql.default_host в конфигурации PHP, после чего можно оставлять параметр server пустым.

Поддержка указания порта через ":port" была добавлена в PHP 3.0B4.

Поддержка указания локального сокета как ":/path/to/socket" была добавлена в PHP 3.0.10.

Подавить вывод ошибок можно добавив @ в начало названия функции (@mysql_connect())

Если второй вызов функции произошёл с теми же аргументами mysql_connect(), новое соединение не будет установлено. Вместо этого функция вернёт ссылку на уже установленное соединение. Параметр new_link может заставить функцию mysql_connect() открыть ещё одно соединение, даже если соединение с аналогичными параметрами уже открыто. Параметр client_flags должен быть комбинацией из следующих констант: MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE, MYSQL_CLIENT_INTERACTIVE.

Замечание: Параметр new_link добавлен в PHP 4.2.0

Параметр client_flags добавлен PHP 4.3.0

Соединение с сервером будет закрыто при завершении исполнения скрипта, если до этого оно не будет закрыто с помощью функции mysql_close().

Пример 1. Пример использования mysql_connect()

<?php
   $link
= mysql_connect("localhost", "mysql_user", "mysql_password")
       or die(
"Could not connect: " . mysql_error());
   print (
"Connected successfully");
  
mysql_close($link);
?>

См. также mysql_pconnect() and mysql_close().



mysql_connect
rui dot batista at netcabo dot pt
31-May-2006 08: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 10: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 09: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 03: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 01: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 02: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 02: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
27-Jun-2003 11: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 08: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
11-Mar-2003 10: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 11: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
26-Mar-2002 03: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_closemysql_create_db>
 Last updated: Tue, 15 Nov 2005