- Тестовое подключение к MySQL из PHP mysqli
- mysql_get_server_info
- Описание
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- User Contributed Notes 3 notes
- mysql_get_host_info
- Описание
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- User Contributed Notes
- PHP host_info() / mysqli_get_host_info() Function
- Syntax
- Object oriented style:
- Procedural style:
- Parameter Values
- Technical Details
- Example — Procedural style
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- PHP mysqli: get_host_info() function
- mysqli_get_host_info() function / mysqli::$host_info
- PHP: Tips of the Day
Тестовое подключение к MySQL из PHP mysqli
Иногда необходимо протестировать работу базы данных, если не удается настроить подключение через сайт или CMS, для этого можно использовать простой PHP скрипт с расширением mysqli.
Скрипт достаточно загрузить в папку вашего сайта и подставить свои значения в файле вместо USER, PASSWORD, BASENAME.
Данный фрагмент кода поможет проверить подключение к базе данных. А также может служить основой для работы с базой данных и выполнения SQL запросов.
$mysqli = new mysqli('localhost', 'USER', 'PASSWORD', 'BASENAME'); if ($mysqli->connect_error) { die('Ошибка подключения (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); } echo 'Соединение установлено. '
. $mysqli->host_info . ""; $result = $mysqli->query("SHOW TABLES;"); while ($row = $result->fetch_row()) { echo "Таблица: "
; } echo 'Версия MYSQL сервера: ' . $mysqli->server_info . "\n"; $mysqli->close(); ?>
Пригодился скрипт для тестирования хостинга Namecheap.
mysql_get_server_info
Данный модуль устарел, начиная с версии PHP 5.5.0, и удалён в PHP 7.0.0. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API. Альтернативы для данной функции:
Описание
Возвращает версию сервера MySQL.
Список параметров
Соединение MySQL. Если идентификатор соединения не был указан, используется последнее соединение, открытое mysql_connect() . Если такое соединение не было найдено, функция попытается создать таковое, как если бы mysql_connect() была вызвана без параметров. Если соединение не было найдено и не смогло быть создано, генерируется ошибка уровня E_WARNING .
Возвращаемые значения
Возвращает версию сервера MySQL в случае успешного выполнения или false в случае возникновения ошибки.
Примеры
Пример #1 Пример использования mysql_get_server_info()
$link = mysql_connect ( ‘localhost’ , ‘mysql_user’ , ‘mysql_password’ );
if (! $link ) die( ‘Ошибка соединения: ‘ . mysql_error ());
>
printf ( «Версия сервера MySQL: %s\n» , mysql_get_server_info ());
?>?php
Результатом выполнения данного примера будет что-то подобное:
Версия сервера MySQL: 4.0.1-alpha
Смотрите также
- mysql_get_client_info() — Возвращает данные о MySQL-клиенте
- mysql_get_host_info() — Возвращает информацию о соединении с MySQL
- mysql_get_proto_info() — Возвращает информацию о протоколе MySQL
- phpversion() — Получает текущую версию PHP
User Contributed Notes 3 notes
An alternative to mysql_get_client_info() is to use the VERSION() function in MySQL language like:
$query = mysql_query ( «SELECT VERSION() as mysql_version» );
?>
The output is the same as mysql_get_client_info()
Here is something I put together because I needed a way to pull the MySQL version number from the server without actually having a connection. This was due to being part of a server info screen prior to installation of a cms. Users need to know if their MySQL is supported or not prior to installation right? 🙂
This will scrape the phpinfo page looking for the MySQL row that says Client API version and return the version number after it. This could also be used to scrape just about anything from the phpinfo page. 🙂
ob_start();
phpinfo(INFO_MODULES);
$info = ob_get_contents();
ob_end_clean();
$info = stristr($info, ‘Client API version’);
preg_match(‘/6.7.67/’, $info, $match);
$gd = $match[0];
echo ‘MySQL: ‘.$gd.’
‘;
This will output:
MySQL: 4.1.22 (which is the version on my server)
I know this is crude but it’s the only thing I could come up with and there isn’t anything like this info available online so here it is. I suck at preg_match and it would be helpful if someone could modify the string here to stand the test of time.
mysql_connect ( ‘localhost’ , ‘user’ , ‘password’ ) or
die( ‘Could not connect: ‘ . mysql_error ());
$a = mysql_get_server_info ();
$b = substr ( $a , 0 , strpos ( $a , «-» ));
echo $b ;
?>
- MySQL
- mysql_affected_rows
- mysql_client_encoding
- mysql_close
- mysql_connect
- mysql_create_db
- mysql_data_seek
- mysql_db_name
- mysql_db_query
- mysql_drop_db
- mysql_errno
- mysql_error
- mysql_escape_string
- mysql_fetch_array
- mysql_fetch_assoc
- mysql_fetch_field
- mysql_fetch_lengths
- mysql_fetch_object
- mysql_fetch_row
- mysql_field_flags
- mysql_field_len
- mysql_field_name
- mysql_field_seek
- mysql_field_table
- mysql_field_type
- mysql_free_result
- mysql_get_client_info
- mysql_get_host_info
- mysql_get_proto_info
- mysql_get_server_info
- mysql_info
- mysql_insert_id
- mysql_list_dbs
- mysql_list_fields
- mysql_list_processes
- mysql_list_tables
- mysql_num_fields
- mysql_num_rows
- mysql_pconnect
- mysql_ping
- mysql_query
- mysql_real_escape_string
- mysql_result
- mysql_select_db
- mysql_set_charset
- mysql_stat
- mysql_tablename
- mysql_thread_id
- mysql_unbuffered_query
mysql_get_host_info
Данный модуль устарел, начиная с версии PHP 5.5.0, и удалён в PHP 7.0.0. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API. Альтернативы для данной функции:
Описание
Описывает тип используемого соединения, указанного переданным дескриптором соединения, включая имя хоста.
Список параметров
Соединение MySQL. Если идентификатор соединения не был указан, используется последнее соединение, открытое mysql_connect() . Если такое соединение не было найдено, функция попытается создать таковое, как если бы mysql_connect() была вызвана без параметров. Если соединение не было найдено и не смогло быть создано, генерируется ошибка уровня E_WARNING .
Возвращаемые значения
Возвращает строку, описывающую тип используемого соединения, указанного переданным дескриптором соединения или false в случае возникновения ошибки.
Примеры
Пример #1 Пример использования mysql_get_host_info()
$link = mysql_connect ( ‘localhost’ , ‘mysql_user’ , ‘mysql_password’ );
if (! $link ) die( ‘Ошибка соединения: ‘ . mysql_error ());
>
printf ( «Тип соединения с MySQL: %s\n» , mysql_get_host_info ());
?>?phpРезультатом выполнения данного примера будет что-то подобное:
Тип соединения с MySQL: Localhost via UNIX socket
Смотрите также
- mysql_get_client_info() — Возвращает данные о MySQL-клиенте
- mysql_get_proto_info() — Возвращает информацию о протоколе MySQL
- mysql_get_server_info() — Возвращает информацию о сервере MySQL
User Contributed Notes
- MySQL
- mysql_affected_rows
- mysql_client_encoding
- mysql_close
- mysql_connect
- mysql_create_db
- mysql_data_seek
- mysql_db_name
- mysql_db_query
- mysql_drop_db
- mysql_errno
- mysql_error
- mysql_escape_string
- mysql_fetch_array
- mysql_fetch_assoc
- mysql_fetch_field
- mysql_fetch_lengths
- mysql_fetch_object
- mysql_fetch_row
- mysql_field_flags
- mysql_field_len
- mysql_field_name
- mysql_field_seek
- mysql_field_table
- mysql_field_type
- mysql_free_result
- mysql_get_client_info
- mysql_get_host_info
- mysql_get_proto_info
- mysql_get_server_info
- mysql_info
- mysql_insert_id
- mysql_list_dbs
- mysql_list_fields
- mysql_list_processes
- mysql_list_tables
- mysql_num_fields
- mysql_num_rows
- mysql_pconnect
- mysql_ping
- mysql_query
- mysql_real_escape_string
- mysql_result
- mysql_select_db
- mysql_set_charset
- mysql_stat
- mysql_tablename
- mysql_thread_id
- mysql_unbuffered_query
PHP host_info() / mysqli_get_host_info() Function
The host_info() / mysqli_get_host_info() function returns the MySQL server hostname and the connection type.
Syntax
Object oriented style:
Procedural style:
Parameter Values
Technical Details
Return Value: Returns a string that represents the MySQL server hostname and the connection type PHP Version: 5+ Example — Procedural style
Return the server hostname and connection type:
if (mysqli_connect_errno()) echo «Failed to connect to MySQL: » . mysqli_connect_error();
exit();
>COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
PHP mysqli: get_host_info() function
mysqli_get_host_info() function / mysqli::$host_info
The mysqli_get_host_info() function / mysqli::$host_info returns the MySQL server hostname and the connection type.
Object oriented style
Procedural style
string mysqli_get_host_info ( mysqli $link )
Name Description Required/Optional connection A link identifier returned by mysqli_connect() or mysqli_init() Required for procedural style only and Optional for Object oriented style Usage: Procedural style
mysqli_get_host_info(connection);
Return value:
A character string representing the server hostname and the connection type.
Version: PHP 5, PHP 7
Example of object oriented style:
/* print host information */ printf("Host info: %s\n", $mysqli->host_info); /* close connection */ $mysqli->close(); ?>
Host info: MySQL host info: localhost via TCP/IP
Example of procedural style:
/* print host information */ printf("Host info: %s\n", mysqli_get_host_info($link)); /* close connection */ mysqli_close($link); ?>
Host info: Localhost via UNIX socket
echo mysqli_get_host_info($con); mysqli_close($con); ?>
MySQL host info: localhost via TCP/IP
Follow us on Facebook and Twitter for latest update.
PHP: Tips of the Day
PHP array delete by value (not key)
Using array_search() and unset, try the following:
if (($key = array_search($del_val, $messages)) !== false)
array_search() returns the key of the element it finds, which can be used to remove that element from the original array using unset(). It will return FALSE on failure, however it can return a false-y value on success (your key may be 0 for example), which is why the strict comparison !== operator is used.
The if() statement will check whether array_search() returned a value, and will only perform an action if it did.
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook