- PHP — AJAX и MySQL
- Пример работы с Ajax, PHP и MySQL
- Example
- Таблица примера работы с Ajax и MySQL
- Пример
- Пример
- Объяснение примера работы с Ajax и MySQL
- Пример
- Файл-обработчик для работы с Ajax и MySQL
- Пример
- PHP: Как получить и отобразить данные из базы данных в PHP с помощью Ajax
- Как получить и отобразить данные из базы данных с помощью Ajax без обновления страницы
- Шаг 1 — Создать базу данных и таблицу
- Шаг 2 — Подключение к базе данных MySQL
- Шаг 3 — Получить данные списка из базы данных
- Шаг 4 — Получение и отображение с использованием Ajax без перезагрузки страницы
- AJAX и PHP — работа с базой данных
- Решение (Пример):
- AJAX и PHP — работа с базой данных : 2 комментария
- How To Return JSON Response in PHP & MySQL using Ajax and jQuery
- Basic Example
- AJAX Integration
- Display by JSON Property
- Display JSON Property in HTML
- Display Dynamic Data Using Response JSON with PHP & MySQL
- Loop the JSON Response
PHP — AJAX и MySQL
В этом уроке мы наглядно проиллюстрируем, насколько просто получить доступ к информации из базы данных с помощью AJAX, мы собираемся создавать запросы MySQL на лету и отображать результаты в виде таблицы HTML.
Пример работы с Ajax, PHP и MySQL
В следующем примере показано, как веб-страница может получать информацию из базы данных с помощью AJAX. Вы можете из выпадающего списка выбрать одного из клиентов и увидите, что, без перезагрузки страницы, необходимая информация будет отображаться ввиде таблицы HTML:
Example
Таблица примера работы с Ajax и MySQL
Пример
// Попытка выполнить запрос на создание таблицы $sql = "CREATE TABLE ajax_demo ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, age int(11) NOT NULL, hometown VARCHAR(30) NOT NULL, job VARCHAR(30) NOT NULL ) "; if(mysqli_query($link, $sql)) < echo "Таблица успешно создана."; >else < echo "ERROR: Не удалось выполнить $sql. " . mysqli_error($link); >// Закрыть соединение mysqli_close($link); ?>
Пример
// Попытка выполнения запроса вставки $sql = "INSERT INTO ajax_demo (firstname, lastname, age, hometown, job) VALUES ('Ivan', 'Ivanov', 30, 'Moskow', 'designer'), ('Stepan', 'Stepanov', 32, 'Kiev', 'manager'), ('Maxim', 'Maxsimov', 33, 'London', 'boss'), ('Irina', 'Sidorova', 35, 'Varshava', 'programmer')"; if(mysqli_query($link, $sql)) < echo "Записи успешно вставлены."; >else < echo "ERROR: Не удалось выполнить $sql. " . mysqli_error($link); >// Закрыть соединение mysqli_close($link); ?>
В результате мы получим следующую таблицу, которую будем исползовать в этом уроке:
Объяснение примера работы с Ajax и MySQL
В приведенном в начале урока примере, когда пользователь выбирает человека в раскрывающемся списке, выполняется функция showUser() . Функция showUser() запускается событием onchange :
Пример
- Создадим объект var xmlhttp = new XMLHttpRequest();
- Создадим функцию xmlhttp.onreadystatechange, которая будет выполняться, когда будет готов ответ сервера if (this.readyState == 4 && this.status == 200)
- Отправим запрос в php-файл getuser.php на сервере
- Обратите внимание, что к URL-адресу добавлен параметр (q) (с содержимым раскрывающегося списка)
Файл-обработчик для работы с Ajax и MySQL
Страница на сервере, вызываемая выше приведенным JavaScript, представляет собой PHP-файл «getuser.php».
Исходный код в файле «getuser.php» выполняет запрос к базе данных MySQL и возвращает результат в таблице HTML:
Пример
table < width: 100%; border-collapse: collapse; >table, td, th < border: 1px solid black; padding: 5px; >th mysqli_select_db($con,"demo"); $sql="SELECT * FROM ajax_demo WHERE = mysqli_query($con,$sql); echo " Firstname Lastname Age Hometown Job "; while($row = mysqli_fetch_array($result)) < echo ""; echo "" . $row['firstname'] . " "; echo "" . $row['lastname'] . " "; echo "" . $row['age'] . " "; echo "" . $row['hometown'] . " "; echo "" . $row['job'] . " "; echo " "; > echo "
"; mysqli_close($con); ?>
Объяснение кода: Когда запрос отправляется из JavaScript в файл PHP, происходит следующее:
- PHP открывает соединение с сервером MySQL
- Выполняется поиск выбранного человека из списка
- Создается таблица HTML, заполняется данными и отправляется обратно в элемент-заполнитель «txtHint».
PHP: Как получить и отобразить данные из базы данных в PHP с помощью Ajax
В этом руководстве вы узнаете, как получать и отображать данные из базы данных в PHP с помощью jQuery ajax.
В этом посте мы создадим список клиентов и добавим кнопку просмотра в этот список клиентов. После этого у нас будут извлекаться данные из базы данных при нажатии кнопки просмотра в PHP и отображать данные на веб-странице без перезагрузки всей веб-страницы с помощью jQuery ajax.
Как получить и отобразить данные из базы данных с помощью Ajax без обновления страницы
Выполните следующие шаги для того, чтоб научиться получать и отображать данные из базы данных MySQL в PHP с помощью ajax без перезагрузки веб-страницы:
Шаг 1 — Создать базу данных и таблицу
Прежде всего, перейдите на панель phpmyadmin и создайте базу данных и таблицу, используя следующий запрос sql:
CREATE DATABASE my_db; CREATE TABLE `customers` ( `id` int(10) UNSIGNED NOT NULL, `fname` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `lname` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_date` date DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Шаг 2 — Подключение к базе данных MySQL
На этом этапе вы создадите файл с именем mydbCon.php и обновите приведенный ниже код в свой файл.
Следующий код используется для создания подключения к базе данных MySQL в PHP. Кроме того, вы можете использовать PHP-код для подключения к базе данных при извлечении, вставке, обновлении или удалении записей из базы данных MySQL с использованием и без использования ajax:
Шаг 3 — Получить данные списка из базы данных
Отображение данных в таблице HTML.
Итак, создайте файл customers.php и добавьте в него следующий код:
Customers List
# First Last Email Action num_rows > 0) : ?> ">View No Data Found Шаг 4 — Получение и отображение с использованием Ajax без перезагрузки страницы
На этом этапе извлеките данные из базы данных с помощью запроса ajax. Поэтому создайте файл ajax-fetch-record.php и отобразите данные из базы данных с помощью ajax без обновления или перезагрузки всей веб-страницы.
Итак, обновите следующий код в файле ajax-fetch-record.php:
Как получить данные из базы данных на php с помощью ajax и jquery, будет выглядеть как на следующем изображении:
Здесь вы узнали, как получать данные из таблицы MySQL в PHP с помощью jQuery ajax без перезагрузки или обновления всей веб-страницы.
AJAX и PHP — работа с базой данных
Динамический показ данных (товар) в зависимости от выбора элемента (категория) в выпадающем списке , используя AJAX.
Решение (Пример):
Создать файл index.php, в котором
Листинг файла подключения к БД auth.php
Листинг файла с AJAX запросом index.php
Создать файл show.php, в котором обрабатываем AJAX запрос
- подключаемся к базе данных для получения списка товаров по ID категории
- выводим полученные товары
Листинг файла для обработки запроса show.php
AJAX и PHP — работа с базой данных : 2 комментария
- Юрий23 января, 2013 в 09:06 Дружище, СПАСИБО.
Искал 2 дня решение.
по всему инету раскинуто как-то заумно, на массивах и т.п. Спасибо, то что надо!
How To Return JSON Response in PHP & MySQL using Ajax and jQuery
In this tutorial, I will share with you how to return JSON response in PHP & MySQL using Ajax & jQuery this is useful to display multiple types of data from server response and process it to our client-side using ajax and jquery. Don’t worry this method is easy we are going to use an array from the server and encode it with JSON format.
Basic Example
Let’s do the basics first we will create a new file called basic.php as you can see below code I created an associative array with first_name & last_name name keys. Then I use json_encode to encode the array into JSON format.
Then this is the result when executing it in the browser.
AJAX Integration
For ajax integration we need to create a simple button in our index.html then a simple ajax function to communicate the above code basic.php.
Let’s code our button with HTML.
Then next is our javascript ajax code. We will create our function named basic() inside scripts.js. Here is the code below:
Then if we will click the button «Basic JSON Response» the result will be like this on the console.
Next, we will parse the response JSON so that we can easily call it as JSON. See the code below.
As you can see we add a new line of code «response = JSON.parse(response);». Kindly see the console result after this code.
As you can see from the result above it is clickable now because we already parse it as JSON from a string.
Display by JSON Property
Now we will display the JSON by property like if you want to display the first_name value only. Here is the code update below:
As you can see below we add a new line of code «console.log(«First Name:» + response.first_name);» now in this code, we only access the first_name value.
Display JSON Property in HTML
Now we will display the specific property on your web page. We will update our HTML code below.
Then also our javascript code inside scripts.js. See below code updates.
As you can see above I add new line of code «$(«#json_first_name»).html(«First Name: » + response.first_name);». I call the ID selector «#json_first_name» and use html() function to display the first_name value from your server.
Now since you have the basic knowledge already of how to Response the JSON we will implement the dynamic data using PHP & MySQL with Ajax.
Display Dynamic Data Using Response JSON with PHP & MySQL
I will share with you the easy method to display the dynamic data from your server-side. In this example, we will display the employee in Edit Employee Modal using ajax and jquery.
Here is the HTML code inside index.html
Our HTML code for modal inside index.html
Edit Employee
Then our PHP code inside get.php as you can see below that I encode the $row variable array from the result query.
query($sql); // Fetch Associative array $row = $results->fetch_assoc(); // Free result set $results->free_result(); // Close the connection after using it $db->close(); // Encode array into json format echo json_encode($row); ?>
Then now we will add our javascript code get() function inside scripts.js.
function get() < $(document).delegate("[data-target='#edit-employee-modal']", "click", function() < var employeeId = $(this).attr('data-id'); // Ajax config $.ajax(< type: "GET", //we are using GET method to get data from server side url: 'get.php', // get the route value data: , //set data beforeSend: function ()/We add this before send to disable the button once we submit it so that we prevent the multiple click > , success: function (response)/once the request successfully process to the server side it will return result here response = JSON.parse(response); $("#edit-form [name=\"id\"]").val(response.id); $("#edit-form [name=\"email\"]").val(response.email); $("#edit-form [name=\"first_name\"]").val(response.first_name); $("#edit-form [name=\"last_name\"]").val(response.last_name); $("#edit-form [name=\"address\"]").val(response.address); > >); >); >
Loop the JSON Response
Since you already know how to display your JSON response to your web page. Now I will give you an example of how to loop the JSON. Below are the screenshot example on listing the employees via ajax with JSON response.
Before we dive in I will show you first a basic code on how to do it. As you can see in the code below I use «$.each(response, function(key,value)
Kindly check the console result below of the above code.
So that’s the basic way on how to loop the JSON. So we will apply it in the advance by displaying the list of employees using the bootstrap list group as you can see the result below:
Now let do the code. First set up our HTML code inside index.html.
Then next our PHP Code inside all.php.
query($sql); // Fetch Associative array $row = $results->fetch_all(MYSQLI_ASSOC); // Free result set $results->free_result(); // Close the connection after using it $db->close(); // Encode array into json format echo json_encode($row); ?>
Then now let’s code the javascript for looping the employee’s result via ajax. You will find this code inside scripts.js with all() functions.
function all() < // Ajax config $.ajax(< type: "GET", //we are using GET method to get all record from the server url: 'all.php', // get the route value success: function (response)/once the request successfully process to the server side it will return result here // Parse the json result response = JSON.parse(response); var html = ""; // Check if there is available records if(response.length) < html += ' '; // Loop the parsed JSON $.each(response, function(key,value) < // Our employee list template html += ''; html += "" + value.first_name +' '+ value.last_name + " (" + value.email + ")" + "
"; html += "" + value.address + "
"; html += ""; html += ""; html += ''; >); html += ''; > else < html += ''; html += 'No records found!'; html += ''; > // Insert the HTML Template and display all employee records $("#employees-list").html(html); > >); >
Now you have the foundation already about JSON Response from your server-side. I hope this article may help you. To see the action capability of this code just click the «Download» button below.
Thank you for reading. Happy Coding!