mysql pconnect php 7
Переход с mysql на mysqli в php 7
На сегодня в php 7 исчезла стандартная команда для работы с БД mysql и большая часть функций, которая с ней связана. Теперь используется mysqli. Он доступен с версии php 5.3. Поэтому на 95% серверах лучше сразу программировать в новом формате под mysqli.
Рассмотрим методы перехода с mysql на mysqli
Рассмотрим создание таблиц:
Старый синтаксис:
mysql_query(«create table IF NOT EXISTS reitingpeopl (id int not null AUTO_INCREMENT, name TEXT(100000) not null, emails TEXT(100000) not null, PRIMARY KEY(id) ) DEFAULT CHARACTER SET utf8 «);
Новый синтаксис:
mysqli_query($connect, «create table IF NOT EXISTS reitingpeopl (id int not null AUTO_INCREMENT, name TEXT(100000) not null, emails TEXT(100000) not null, PRIMARY KEY(id) ) DEFAULT CHARACTER SET utf8 «);
Теперь рассмотрим циклы:
Старый синтаксис:
$podresult = mysql_query(«select * from reitingpeopl where «);
while ($podrow=mysql_fetch_array($podresult))
Новый синтаксис:
$podresult = mysqli_query($connect, «select * from reitingpeopl where «);
while ($podrow=mysqli_fetch_array($podresult))
Еще популярные примеры команд (просто добавьте на конце i):
mysqli_fetch_row()
mysqli_fetch_assoc()
mysqli_fetch_array()
mysqli_num_rows()
mysqli_insert_id()
mysqli_close()
Если что-то вы не нашли, то это можно будет легко отыскать в справочниках. В любом случае mysqli в php 7 работает намного быстрее, чем mysql, поэтому не задумываясь переходите в новый формат!
mysql_connect
mysql_connect — Открывает соединение с сервером MySQL
Данный модуль устарел, начиная с версии PHP 5.5.0, и удалён в PHP 7.0.0. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API. Альтернативы для данной функции:
Описание
Открывает новое соединение с сервером MySQL или использует уже существующее.
Список параметров
Сервер MySQL. Может также включать номер порта, например, «hostname:port» или путь к локальному сокету, например, «:/path/to/socket» для локального сервера.
Если PHP-директива mysql.default_host не определена (по умолчанию), то значением по умолчанию является ‘localhost:3306’. В SQL safe mode этот параметр игнорируется и всегда используется значение ‘localhost:3306’.
Имя пользователя. Значение по умолчанию определяется директивой mysql.default_user. В SQL safe mode этот параметр будет проигнорирован и будет использован пользователь, владеющий процессом сервера.
Пароль. Значение по умолчанию определяется директивой mysql.default_password. В SQL safe mode этот параметр будет проигнорирован и в качестве пароля будет использована пустая строка.
Если второй вызов функции mysql_connect() произошёл с теми же аргументами, то новое соединение не будет установлено. Вместо этого функция вернёт ссылку на уже установленное соединение. Параметр new_link может заставить функцию mysql_connect() открыть ещё одно соединение, даже если соединение с аналогичными параметрами уже открыто. В SQL safe mode этот параметр игнорируется.
Возвращаемые значения
Возвращает дескриптор соединения с MySQL в случае успешного выполнения или false в случае возникновения ошибки.
Примеры
Пример #1 Пример использования mysql_connect()
Пример #2 Пример использования mysql_connect() с синтаксисом hostname:port
Пример #3 Пример использования mysql_connect() с синтаксисом «:/path/to/socket»
// соединяемся к localhost по сокету, т.е. /tmp/mysql.sock
Примечания
При указании параметру server значения «localhost» или «localhost:port» клиентская библиотека MySQL будет пытаться соединиться с локальным сокетом. Если вы всё же хотите использовать TCP/IP, используйте адрес «127.0.0.1» вместо «localhost». Если клиентская библиотека пытается подключиться не к тому локальному сокету, это можно исправить через указание директивы в конфигурации PHP, после чего можно оставлять параметр server пустым.
Смотрите также
mysql_pconnect — Устанавливает постоянное соединение с сервером MySQL
Данное расширение устарело, начиная с версии PHP 5.5.0, и будет удалено в будущем. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API и соответствующий FAQ для получения более подробной информации. Альтернативы для данной функции:
Описание
Устанавливает постоянное соединение с сервером MySQL.
mysql_pconnect() работает аналогично mysql_connect() с двумя важными отличиями.
Во-первых, при соединении функция пытается найти уже открытый (постоянный) указатель на тот же сервер с тем же пользователем и паролем. Если он найден, возвращён функцией будет именно он, вместо открытия нового соединения.
Во-вторых, соединение с SQL-сервером не будет закрыто, когда работа скрипта закончится. Вместо этого, оно останется рабочим для будущего использования ( mysql_close() также не закрывает постоянные соединения, открытые mysql_pconnect() ).
Соединения такого типа называют ‘постоянными’.
Список параметров
Сервер MySQL. Может также включать номер порта, например, «hostname:port» или путь к локальному сокету, например, «:/path/to/socket» для локального хоста.
Если директива mysql.default_host не определена (по умолчанию), то по умолчанию используется значение ‘localhost:3306’
Имя пользователя. По умолчанию используется имя пользователя, владеющего серверным процессом.
Пароль. По умолчанию используется пустая строка.
Возвращаемые значения
Возвращает дескриптор постоянного соединения MySQL в случае успеха, и FALSE в случае ошибки.
Список изменений
Примечания
Учтите, что соединения такого типа работают только, если PHP установлен как модуль. За дополнительной информацией обращайтесь к разделу «Постоянные соединения с базами данных».
Использование постоянных соединений может потребовать некоторой настройки Apache и MySQL. Убедитесь, что вы не превысите максимальное число дозволенных соединений в MySQL.
Можно подавить сообщение об ошибке при неудачном соединении поставив перед вызовом функции оператор @.
mysql_pconnect
mysql_pconnect — Устанавливает постоянное соединение с сервером MySQL
Данный модуль устарел, начиная с версии PHP 5.5.0, и удалён в PHP 7.0.0. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API. Альтернативы для данной функции:
Описание
Устанавливает постоянное соединение с сервером MySQL.
mysql_pconnect() работает аналогично mysql_connect() с двумя важными отличиями.
Во-первых, при соединении функция пытается найти уже открытый (постоянный) указатель на тот же сервер с тем же пользователем и паролем. Если он найден, возвращён функцией будет именно он, вместо открытия нового соединения.
Во-вторых, соединение с SQL-сервером не будет закрыто, когда работа скрипта закончится. Вместо этого, оно останется рабочим для будущего использования ( mysql_close() также не закрывает постоянные соединения, открытые mysql_pconnect() ).
Соединения такого типа называют ‘постоянными’.
Список параметров
Сервер MySQL. Может также включать номер порта, например, «hostname:port» или путь к локальному сокету, например, «:/path/to/socket» для локального хоста.
Если директива mysql.default_host не определена (по умолчанию), то по умолчанию используется значение ‘localhost:3306’
Имя пользователя. По умолчанию используется имя пользователя, владеющего серверным процессом.
Пароль. По умолчанию используется пустая строка.
Возвращаемые значения
Возвращает дескриптор постоянного соединения MySQL в случае успешного выполнения, и false в случае возникновения ошибки.
Примечания
Учтите, что соединения такого типа работают только, если PHP установлен как модуль. За дополнительной информацией обращайтесь к разделу «Постоянные соединения с базами данных».
Использование постоянных соединений может потребовать некоторой настройки Apache и MySQL. Убедитесь, что вы не превысите максимальное число дозволенных соединений в MySQL.
Смотрите также
User Contributed Notes 28 notes
Normally you do NOT want to use mysql_pconnect. This function is designed for environments which have a high overhead to connecting to the database. In a typical MySQL / Apache / PHP environment, Apache will create many child processes which lie in idle waiting for a web request to be assigned to them. Each of these child processes will open and hold its own MySQL connection. So if you have a MySQL server which has a limit of 50 connections, but Apache keeps more than 50 child processes running, each of these child processes can hold a connection to your MySQL server, even while they are idle (idle httpd child processes don’t lend their MySQL connection to other httpd children, they hold their own). So even if you only have a few pages which actually connect to MySQL on a busy site, you can run out of connections, with all of them not actually being used.
In general use mysql_connect() for connecting to MySQL unless that connection takes a long time to establish.
(using PHP v5.3.2)
This might help other people who are running into a similar issue. I would occasionally get this error in my apache error log:
PHP Warning: mysql_pconnect(): MySQL server has gone away
It appears the persistent connection mysql_pconnect() was returning had timed out and mysql_pconnect() didn’t detect it. To address this issue I added some code to check for this case using mysql_ping() and request another connection from mysql_pconnect() if this situation occurred. It appears that the combination of the checking for the time out with mysql_ping( ) and re-requesting the connection with mysql_pconnect( ) either caused the original connection to re-connect or forced mysql_pconnect() to recognize that the connection had timed out and request a new one. The documentation for mysql_ping( ) says that it will force a re-connect if it detects a timeout, however comments on the documentation page mention that this feature has been disabled for some time. Anyways here is the code I used, hope it helps:
mysql_pconnect(«127.0.0.1:4444», «user», «pass»)
would connect to localhost on port 4444
(useful for ssh tunneling etc)
in response to uthayakutty76 at yahoo dot com’s
30-Jun-2003 12:31 post:
————————————————————
. The problem is that the connection to the MySQL
servers is interrupted very quickly or there is not
connection at all. We found out that when using the
domain of the server instead of «localhost» problems
occur.
————————————————————
try setting the wait_timeout variable in my.cnf for
mysql very high so the connections aren’t ever idle for
that amount of time. ridiculous really, but it works for
localhost or remote database server where as the
localhost solution only works if the database is local i
think.
I had some problems when connecting to a remote server with mysql_pconnect and using the flag MYSQL_CLIENT_COMPRESS. Sometimes it connect, but many times it give me the error:
Warning: mysql_pconnect(): Unknown database ‘XXXXX’
If you have the same problem, try using mysql_connect instead. It worked fine for me. The script will take a long to reconnect each time the page is reloaded, but it will transfer data with compression. This is a little more secure than to send plain data over the Internet and also more faster when transmiting large amount of data.
Here’s a recap of important reasons NOT to use persistent connections:
* When you lock a table, normally it is unlocked when the connection closes, but since persistent connections do not close, any tables you accidentally leave locked will remain locked, and the only way to unlock them is to wait for the connection to timeout or kill the process. The same locking problem occurs with transactions. (See comments below on 23-Apr-2002 & 12-Jul-2003)
* Normally temporary tables are dropped when the connection closes, but since persistent connections do not close, temporary tables aren’t so temporary. If you do not explicitly drop temporary tables when you are done, that table will already exist for a new client reusing the same connection. The same problem occurs with setting session variables. (See comments below on 19-Nov-2004 & 07-Aug-2006)
* If PHP and MySQL are on the same server or local network, the connection time may be negligible, in which case there is no advantage to persistent connections.
* Apache does not work well with persistent connections. When it receives a request from a new client, instead of using one of the available children which already has a persistent connection open, it tends to spawn a new child, which must then open a new database connection. This causes excess processes which are just sleeping, wasting resources, and causing errors when you reach your maximum connections, plus it defeats any benefit of persistent connections. (See comments below on 03-Feb-2004, and the footnote at http://devzone.zend.com/node/view/id/686#fn1)
Be warned if you use different parameters for mysql_pconnect() in different scripts on server: PHP can create single persistent connection for every set of parameters in each process up to mysql.max_persistent (PHP directive) per process. So even if you have MaxClients Apache directive set lesser then max_connections MySQL directive, you can easily get Too many connections MySQL error.
Solution: For servers with potentially unlimited set of connection parameters, forbid persistent connection with mysql.allow_persistent=Off.
Here’s a nifty little class which will load balance across multiple replicated MySQL server instances, using persistent connections, automatically removing failed MySQL servers from the pool.
You would ONLY use this for queries, never inserts/updates/deletes, UNLESS you had a multi-master situation where updates to any database serverautomatically replicate to the other servers (I don’t know whether that’s possible with MySQL).
Using this class, you get a connection to a MySQL server like this:
$con = MySQLConnectionFactory::create();
You also may consider using pconnect if you have transactions that span multiple pages. For example, in applications that I develop, I start a transaction on the moment I query selecting the data that the user plans on editing. I then commit the transactions after the user hits the submit button and the data is committed.
I cannot simply use mysql_connect as then the connection would be terminated at the end of the page and if I did not commit my transaction, it is automatically rolled back.
I would like to comment on the post from dfischer at qualcomm dot com that proposes spanning transactions over multiple application invocations, in case someone is bold enough to try it.
I’ll assume the table types being used are one of those that support transactions, such as InnoDB or BerkeleyDB.
First, there is a question of whether this would work at all. To work at all, the transaction context would have to be preserved across all the invocations of the php code through the web server. Reading the description of http://www.php.net/manual/en/features.persistent-connections.php maintaining transaction context would be at best a coincidence. It would be interesting to find out that this does work on occasion and to understand the ramifications of such behavior. If I happened to get your connection and my action was a cancel, your updates might be gone.
Second, if such a thing did work (occassionally or always), there would be performance implications as the underlying database managed transactions that were pretty much open-ended. A few long-running transactions would likely eat up many resources in a short time and the likelihood of concurrency conflicts could rise. If the mysql_pconnect behavior is to keep transaction open at the end of php processing, then it would probably be better to not define transactions when using mysql_pconnect. And, transactions that were never closed by code (user went out to lunch and got hit by a bus) could hold resources for quite some time (maybe until after rehab).
So, even if such a scheme COULD work, it is not a good idea. The transaction should be committed or rolled back at the end of the user request processing. This allows the DBMS to properly manage resource ultilization and keeps bad things from happening to good data. If mysql_pconnect does not coordinate well with the transaction component of the database engine to always end a transaction at the end of processing a request, then mysql_pconnect should never be used where begin transaction is used.
mysql_pconnect
mysql_pconnect — Устанавливает постоянное соединение с сервером MySQL
Данное расширение устарело, начиная с версии PHP 5.5.0, и будет удалено в будущем. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API и соответствующий FAQ для получения более подробной информации. Альтернативы для данной функции:
Описание
Устанавливает постоянное соединение с сервером MySQL.
mysql_pconnect() работает аналогично mysql_connect() с двумя важными отличиями.
Во-первых, при соединении функция пытается найти уже открытый (постоянный) указатель на тот же сервер с тем же пользователем и паролем. Если он найден, возвращён функцией будет именно он, вместо открытия нового соединения.
Во-вторых, соединение с SQL-сервером не будет закрыто, когда работа скрипта закончится. Вместо этого, оно останется рабочим для будущего использования ( mysql_close() также не закрывает постоянные соединения, открытые mysql_pconnect() ).
Соединения такого типа называют ‘постоянными’.
Список параметров
Сервер MySQL. Может также включать номер порта, например, «hostname:port» или путь к локальному сокету, например, «:/path/to/socket» для локального хоста.
Если директива mysql.default_host не определена (по умолчанию), то по умолчанию используется значение ‘localhost:3306’
Имя пользователя. По умолчанию используется имя пользователя, владеющего серверным процессом.
Пароль. По умолчанию используется пустая строка.
Возвращаемые значения
Возвращает дескриптор постоянного соединения MySQL в случае успеха, и FALSE в случае ошибки.
Список изменений
Примечания
Учтите, что соединения такого типа работают только, если PHP установлен как модуль. За дополнительной информацией обращайтесь к разделу «Постоянные соединения с базами данных».
Использование постоянных соединений может потребовать некоторой настройки Apache и MySQL. Убедитесь, что вы не превысите максимальное число дозволенных соединений в MySQL.
Можно подавить сообщение об ошибке при неудачном соединении поставив перед вызовом функции оператор @.
Смотрите также
Коментарии
PHP 4.1.1 running with Apache under Linux doesn’t seem to be doing all necessary flushing when handling persistant mysql connections. Try it out for yourself. Create a temporary table in a pconnect session, add rows (non unique), select/display and drop the table. Now reload your script multiple times, you will see that your results are not consistent, even though you are creating a new table everytime and dropping it..
I had my share of problems with pconnect and suggest you don’t use it unless absolutely necessary. In that case make sure you test your results for consistency, especially when your queries involve temporary tables or mysql session variables.
mysql_pconnect(«127.0.0.1:4444», «user», «pass»)
would connect to localhost on port 4444
(useful for ssh tunneling etc)
You can solve problem with persistent connections setting directive mysql.allow_persistent = Off in php configuration file. The users whitch will try to create persistant connetion /mysql_pconnect()/ will be connected to db
with nonpersistant connection /mysql_connect()/
For more info see user notes at section Persistant Connections. features.persistent-connections
—
http://www.id.com.ua Ilya Rudenko
I had some problems when connecting to a remote server with mysql_pconnect and using the flag MYSQL_CLIENT_COMPRESS. Sometimes it connect, but many times it give me the error:
Warning: mysql_pconnect(): Unknown database ‘XXXXX’
If you have the same problem, try using mysql_connect instead. It worked fine for me. The script will take a long to reconnect each time the page is reloaded, but it will transfer data with compression. This is a little more secure than to send plain data over the Internet and also more faster when transmiting large amount of data.
in response to uthayakutty76 at yahoo dot com’s
30-Jun-2003 12:31 post:
————————————————————
. The problem is that the connection to the MySQL
servers is interrupted very quickly or there is not
connection at all. We found out that when using the
domain of the server instead of «localhost» problems
occur.
————————————————————
try setting the wait_timeout variable in my.cnf for
mysql very high so the connections aren’t ever idle for
that amount of time. ridiculous really, but it works for
localhost or remote database server where as the
localhost solution only works if the database is local i
think.
Be warned if you use different parameters for mysql_pconnect() in different scripts on server: PHP can create single persistent connection for every set of parameters in each process up to mysql.max_persistent (PHP directive) per process. So even if you have MaxClients Apache directive set lesser then max_connections MySQL directive, you can easily get Too many connections MySQL error.
Solution: For servers with potentially unlimited set of connection parameters, forbid persistent connection with mysql.allow_persistent=Off.
Normally you do NOT want to use mysql_pconnect. This function is designed for environments which have a high overhead to connecting to the database. In a typical MySQL / Apache / PHP environment, Apache will create many child processes which lie in idle waiting for a web request to be assigned to them. Each of these child processes will open and hold its own MySQL connection. So if you have a MySQL server which has a limit of 50 connections, but Apache keeps more than 50 child processes running, each of these child processes can hold a connection to your MySQL server, even while they are idle (idle httpd child processes don’t lend their MySQL connection to other httpd children, they hold their own). So even if you only have a few pages which actually connect to MySQL on a busy site, you can run out of connections, with all of them not actually being used.
In general use mysql_connect() for connecting to MySQL unless that connection takes a long time to establish.
You also may consider using pconnect if you have transactions that span multiple pages. For example, in applications that I develop, I start a transaction on the moment I query selecting the data that the user plans on editing. I then commit the transactions after the user hits the submit button and the data is committed.
I cannot simply use mysql_connect as then the connection would be terminated at the end of the page and if I did not commit my transaction, it is automatically rolled back.
I would like to comment on the post from dfischer at qualcomm dot com that proposes spanning transactions over multiple application invocations, in case someone is bold enough to try it.
I’ll assume the table types being used are one of those that support transactions, such as InnoDB or BerkeleyDB.
First, there is a question of whether this would work at all. To work at all, the transaction context would have to be preserved across all the invocations of the php code through the web server. Reading the description of features.persistent-connections maintaining transaction context would be at best a coincidence. It would be interesting to find out that this does work on occasion and to understand the ramifications of such behavior. If I happened to get your connection and my action was a cancel, your updates might be gone.
Second, if such a thing did work (occassionally or always), there would be performance implications as the underlying database managed transactions that were pretty much open-ended. A few long-running transactions would likely eat up many resources in a short time and the likelihood of concurrency conflicts could rise. If the mysql_pconnect behavior is to keep transaction open at the end of php processing, then it would probably be better to not define transactions when using mysql_pconnect. And, transactions that were never closed by code (user went out to lunch and got hit by a bus) could hold resources for quite some time (maybe until after rehab).
So, even if such a scheme COULD work, it is not a good idea. The transaction should be committed or rolled back at the end of the user request processing. This allows the DBMS to properly manage resource ultilization and keeps bad things from happening to good data. If mysql_pconnect does not coordinate well with the transaction component of the database engine to always end a transaction at the end of processing a request, then mysql_pconnect should never be used where begin transaction is used.