Php check mysql host

Тестовое подключение к 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 ());
?>

Результатом выполнения данного примера будет что-то подобное:

Версия сервера 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 ());
    ?>

    Результатом выполнения данного примера будет что-то подобное:

    Тип соединения с 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();
      >

      Unlock Full Access 50% off

      COLOR PICKER

      colorpicker

      Join our Bootcamp!

      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

      Источник

      Читайте также:  Научиться программировать в python
Оцените статью