Тестовое подключение к MySQL из PHP mysqli
Иногда необходимо протестировать работу базы данных, если не удается настроить подключение через сайт или CMS, для этого можно использовать простой PHP скрипт с расширением mysqli.
Скрипт достаточно загрузить в папку вашего сайта и подставить свои значения в файле вместо USER, PASSWORD, BASENAME.
Данный фрагмент кода поможет проверить подключение к базе данных. А также может служить основой для работы с базой данных и выполнения SQL запросов.
Пригодился скрипт для тестирования хостинга Namecheap.
Friendhosting — Разумные цены на хостинг
VDS/VPS сервер от 3.49€ в месяц. Много ресурсов. Высокая надежность. Гибкое управление. Удобная оплата. Настройка под вас!
Антидетект браузер Dolphin бесплатно до 10 профилей
Dolphin разработан для работы с такими сложными ресурсов, как Google, Facebook и Coinlist.
Английский для IT‑специалистов по Skype
Персональные занятия по разумным ценам. 80% разговорной практики. Персональный график!
Как проверить подключение к базе данных PHP MySQL с помощью скрипта
MySQL — популярная система управления базами данных, а PHP — язык сценариев на стороне сервера, подходящий для веб-разработки; вместе с HTTP-серверами Apache или Nginx являются различными компонентами стека LAMP (Linux Apache MySQL/MariaDB PHP) или LEMP (Linux Nginx MySQL/MariaDB PHP).
Если вы веб-разработчик, возможно, вы установили эти программные пакеты или использовали их для настройки локального веб-сервера в своей системе. Чтобы ваш веб-сайт или веб-приложение могло хранить данные, ему нужна база данных, такая как MySQL/MariaDB.
Чтобы пользователи веб-приложения могли взаимодействовать с информацией, хранящейся в базе данных, на сервере должна быть запущена программа, которая выбирает запросы от клиента и передает их серверу.
В этом руководстве мы объясним, как проверить соединение с базой данных MySQL с помощью файла PHP. Прежде чем двигаться дальше, убедитесь, что в системе должна быть установлена LAMP или LEMP, в противном случае следуйте этим инструкциям по настройке.
- Установите стек LAMP (Linux, Apache, MariaDB или MySQL и PHP) в Debian 9
- Как установить LAMP с PHP 7 и MariaDB 10 в Ubuntu 16.10
- Установка LAMP (Linux, Apache, MariaDB, PHP/PhpMyAdmin) в RHEL/CentOS 7.0
- Как установить LEMP (Linux, Nginx, MariaDB, PHP-FPM) на Debian 9 Stretch
- Как установить Nginx, MariaDB 10, PHP 7 (стек LEMP) в версии 16.10/16.04
- Установите последнюю версию Nginx 1.10.1, MariaDB 10 и PHP 5.5/5.6 на RHEL/CentOS 7/6 и Fedora 20–26.
Быстрый тест подключения к базе данных MySQL с использованием скрипта PHP
Чтобы быстро проверить соединение PHP MySQL DB, мы будем использовать следующий удобный сценарий в виде файла db-connect-test.php .

Теперь измените имя базы данных, пользователя базы данных и пароль пользователя, а также хост на свои локальные значения.
Сохраните и закройте файл. Теперь запустите его следующим образом: он должен напечатать общее количество таблиц в указанной базе данных.

Вы можете выполнить перекрестную проверку вручную, подключившись к серверу базы данных и указав общее количество таблиц в конкретной базе данных.
Вы также можете ознакомиться со следующими статьями по теме.
- Как найти файлы конфигурации MySQL, PHP и Apache
- 12 полезных способов использования командной строки PHP, которые должен знать каждый пользователь Linux
- Как скрыть номер версии PHP в заголовке HTTP
Есть ли у вас какой-либо другой способ или сценарий для проверки подключения к базе данных MySQL? Если да, то используйте для этого форму обратной связи ниже.
mysql_ping
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
Description
Checks whether or not the connection to the server is working. If it has gone down, an automatic reconnection is attempted. This function can be used by scripts that remain idle for a long while, to check whether or not the server has closed the connection and reconnect if necessary.
Note:
Automatic reconnection is disabled by default in versions of MySQL >= 5.0.3.
Parameters
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
Return Values
Returns true if the connection to the server MySQL server is working, otherwise false .
Examples
Example #1 A mysql_ping() example
$conn = mysql_connect ( ‘localhost’ , ‘mysqluser’ , ‘mypass’ );
$db = mysql_select_db ( ‘mydb’ );
/* Assuming this query will take a long time */
$result = mysql_query ( $sql );
if (! $result ) <
echo ‘Query #1 failed, exiting.’ ;
exit;
>
/* Make sure the connection is still alive, if not, try to reconnect */
if (! mysql_ping ( $conn )) <
echo ‘Lost connection, exiting after query #1’ ;
exit;
>
mysql_free_result ( $result );
/* So the connection is still alive, let’s run another query */
$result2 = mysql_query ( $sql2 );
?>
See Also
- mysql_thread_id() — Return the current thread ID
- mysql_list_processes() — List MySQL processes
User Contributed Notes 7 notes
mysql_ping() is really helpful when you have this annoying error:
MYSQL Error 2006 Server has gone away
For CI users:
In 1.7.2 version of codeigniter, there is a function
that uses mysql_ping() to reestablish the timed out connection.
This function is specially useful when developing social media sites that uses hundreds of connections to the db such asinserting or selecting.
When using the mysql_ping command under php 5.1.2 and mysql 5.0, I was having problems with the auto-reconnect «feature», mainly that when the connection was severed, a mysql_ping would not automatically re-establish the connection to the database.
The connection to the DB is dropped when the time without a query excedes the wait_timeout value in my.cnf. You can check your wait_timeout by running the query «SHOW VARIABLES;»
If you’re having problems auto-reconnecting when the connection is dropped, use this code:
$conn = mysql_connect ( ‘localhost’ , ‘user’ , ‘pass’ );
mysql_select_db ( ‘db’ , $conn );
if (! mysql_ping ( $conn )) <
//here is the major trick, you have to close the connection (even though its not currently working) for it to recreate properly.
mysql_close ( $conn );
$conn = mysql_connect ( ‘localhost’ , ‘user’ , ‘pass’ );
mysql_select_db ( ‘db’ , $conn );
>
How do I check if PHP is connected to a database already?
Update: From PHP 5.5 onwards, use mysqli_ping() instead.
Pings a server connection, or tries to reconnect if the connection has gone down.
Alternatively, a second (less reliable) approach would be:
![]()
Try using PHP’s mysql_ping function:
You will need to prepend the «@» to suppose the MySQL Warnings you’ll get for running this function without being connected to a database.
There are other ways as well, but it depends on the code that you’re using.