TECT

Simple PHP Mysql Connection Test Script Tutorial Guide

As a php programmer, sometimes you need to create scripts with an install for the installation of the script. and you want to test the mysql database connection before you install it. today i was writing a script and i wanted to take the user through the installation process and one of the steps was to test the mysql database connections, if the connections fails, then the user is prompted to enter the database details again, if its successful, then it continues with the next step in the installation process. so you can use this:

OPTION 1 — IF you dont want to create the files yourself, Webune has provided the full script, you can download the .zip file by going to this post: How To Test Mysql Database Connection

OPTION 2 — You can follow the steps below to create the script yourself:

1. first step is to copy and paste the following code into your texteditor. if you are using windows, you can use notepad.

 else < $page_title = 'Test MySQL step '.$step; >############## BEGIN FUNCTIONS ############################## # FUNCTION TO TEST USERNAME AND PASSWORD IN MYSQL HOST function db_connect($server, $username, $password, $link = 'db_link') < global $$link, $db_error; $db_error = false; if (!$server) < $db_error = 'No Server selected.'; return false; >$$link = @mysql_connect($server, $username, $password) or $db_error = mysql_error(); return $$link; > # FUNCTION TO SELECT DATABASE ACCESS function db_select_db($database) < echo mysql_error(); return mysql_select_db($database); ># FUNCTION TO TEST DATABASE ACCESS function db_test_create_db_permission($database) < global $db_error; $db_created = false; $db_error = false; if (!$database) < $db_error = 'No Database selected.'; return false; >if ($db_error) < return false; >else < if ([email protected]_select_db($database)) < $db_error = mysql_error(); return false; >else < return true; >return true; > > function step1 ($error) < echo '

'.$error.'


'; ?>
mysql hostname:
"> (usually "localhost" or enter IP Address of MySQL Server)
mysql username:
">
mysql username password:
">
mysql database name:
">
?> Webune MYSQL TEST -

> else < $error = $db_error; >if ($db_error != false) < $error = "failed"; echo step1($db_error); >else < echo '

Congratulations!

Connected Successful to database Continue >> '; > > else < $error = "ERROR: please provide a hostname"; echo step1($error); >break; default: echo step1('Step 1'); break; > ?>
Script Courtesy of Webune PHP/Mysql Hosting

2. save the file as testmysql.php and upload to your website. NOTE: you must have php and mysql for this sample script to work

3. now open testmysql.php with your browser ( http://www.example.com/testmysql.php ), you will see if it fails or if it is able to connect successful

UPDATE: 12/19/2012 Thanks for your comments. I see that some of you have had trouble with the code. I have tested it again and it works ok on my apache server using XAMPP on my windows 7 laptop. So I created a short video to show you as proof that it works.

Источник

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

Источник

Тест с помощью пхп, проверка ответов с бд

Как организовать заливку ответов в радио из бд и проверку из неё же правильных ответов. Нехрена не понимаю, я просто в отчаянии. SQL немного учили, js немного учили, базу создать на денвере могу, с php никак

Уточнение ответов на тест
Ребята, помогите обосновать ответы на пару вопросов в тесте. Вопрос 1 верные варианты ответа.

Варианты ответов (тест)
Если derived class (Class2) содержит переопределеную функцию из the base class (Class1), как может.

Тест. Присваивание ответов RadioButton
Тест сделал. Решил варианты ответов присваивать в Радиобаттоны, но почемуто они не меняются.

Случайное размещение ответов на тест
Здравствуйте! Есть программа — тест. Есть документ, где вопросы, ответы и верный вариант ответа.

Эксперт PHP

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
      $location = "localhost"; // Хост базы $dbname = "mybase"; // Название БД MySQL $dbuser = "root"; // Пользователь MySQL $dbpass = ""; // Пароль пользователя // Устанавливаем коннект с MySQL $dbconnect = @mysql_connect($location, $dbuser, $dbpass); //Выбираем БД MySQL @mysql_select_db($dbname, $dbconnect); if (!$dbconnect) { echo "Нет коннекта"; exit (); } // Выбираем ВСЕ ответы для данного вопроса из БД $allquest = mysql_query("SELECT * FROM answers WHERE for_id='1'"); // Если нажата кнопка "ОК" if(isset($_POST['sbmanswer'])) { // Тут проверяем if(mysql_num_rows(mysql_query("SELECT * FROM answers WHERE answer']."'&&believed='1'"))>0) { echo "Ответ верен

"
; } else { echo "Ответ не верен

"
; } } ?> Тут ваш вопрос:
// В цикле выводим все ответы на этот вопрос while($questions = mysql_fetch_array($allquest)) { ?>
} ?>

Для начала нужно создать БД mysql, в ней таблицу «answers» с такими полями:
id (ID вопроса в БД, он будет подставляться при выводе ответов к вопросу)
for_id (ID ответа, для которого предназначен данный ответ)
answer (Текст ответа, например «Ответ №1»)
believed (Этот столбец нужен для проверки, верен ли ответ. В него ставим при INSERT’e единицу если ответ верен)

Добавлено через 10 минут
P.S. Естественно, это код будет работать только с одним вопросом (его > 1

ЦитатаСообщение от Lyodik Посмотреть сообщение

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
      $location = "localhost"; // Хост базы $dbname = "mybase"; // Название БД MySQL $dbuser = "root"; // Пользователь MySQL $dbpass = ""; // Пароль пользователя // Устанавливаем коннект с MySQL $dbconnect = @mysql_connect($location, $dbuser, $dbpass); //Выбираем БД MySQL @mysql_select_db($dbname, $dbconnect); if (!$dbconnect) { echo "Нет коннекта"; exit (); } // Выбираем ВСЕ ответы для данного вопроса из БД $allquest = mysql_query("SELECT * FROM answers WHERE for_id='1'"); // Если нажата кнопка "ОК" if(isset($_POST['sbmanswer'])) { // Тут проверяем if(mysql_num_rows(mysql_query("SELECT * FROM answers WHERE answer']."'&&believed='1'"))>0) { echo "Ответ верен

"
; } else { echo "Ответ не верен

"
; } } ?> Тут ваш вопрос:
// В цикле выводим все ответы на этот вопрос while($questions = mysql_fetch_array($allquest)) { ?>
} ?>

Для начала нужно создать БД mysql, в ней таблицу «answers» с такими полями:
id (ID вопроса в БД, он будет подставляться при выводе ответов к вопросу)
for_id (ID ответа, для которого предназначен данный ответ)
answer (Текст ответа, например «Ответ №1»)
believed (Этот столбец нужен для проверки, верен ли ответ. В него ставим при INSERT’e единицу если ответ верен)

Добавлено через 10 минут
P.S. Естественно, это код будет работать только с одним вопросом (его

Источник

How to Test PHP MySQL Database Connection Using Script

MySQL is a popular database management system while PHP is a server-side scripting language suitable for web development; together with Apache or Nginx HTTP servers, are the different components of the LAMP (Linux Apache MySQL/MariaDB PHP) or LEMP (Linux Nginx MySQL/MariaDB PHP) stack receptively.

If you are a web developer then you might have installed these software packages or used them to setup a local web server on your system. In order for your website or web application to store data, it needs a database such as MySQL/MariaDB.

For the web application users to interact with the information stored in the database, there must be a program running on the server to pick requests from client and pass to the server.

In this guide, we will explain how to test a MySQL database connection using a PHP file. Before moving further, make sure you must have LAMP or LEMP installed on the system, if not follow these tutorials to setup.

Setup LAMP Stack on Linux Systems

Setup LEMP Stack on Linux Systems

Quick MySQL Database Connection Test Using PHP Script

To do a quick PHP MySQL DB connection test, we will use a following handy script as file db-connect-test.php .

Script to Test PHP MySQL DB Connection

Now change the database name, database user and user password as well as the host to your local values.

$dbname = 'name'; $dbuser = 'user'; $dbpass = 'pass'; $dbhost = 'host';

Save and close the file. Now run it as follows; it should print the total number of tables in the specified database.

MySQL DB Connection Test

You can cross check manually by connecting to the database server and listing the total number of tables in the particular database.

You may also like to check out these following related articles.

Do you have any other way or script to test a MySQL DB connection? If yes, then use the feedback form below to do that.

Источник

Читайте также:  Разделитель в питоне sep
Оцените статью