- Вывод данных в html таблицу , через php
- Вывод HTML-таблицы с функцией сортировки на PHP + MySQL
- Вывод:
- Результат:
- Сортировка в шапке таблицы
- Вывод:
- Результат:
- Сортировка в виде списка
- Вывод:
- Сортировка полем select
- Вывод:
- Display Data in an HTML Table Using PHP & MySQL
- Steps to Display Data From MySQL Database with PHP
- 1. Connect PHP to MySQL Database
- 2. Insert Data Into PHPMyAdmin Table
- 3. Fetch Data From MySQL Table
- 4. Display Data in HTML Table
- 5. Test Yourself to insert data
- More Methods to display Data in HTML Table with PHP
- Display Data using MySQLi Procedure
- Display Data Using MySQLi Object-Oriented
- Display Data Using PDO
- Display Data Using Prepared Statement
- Related posts:
Вывод данных в html таблицу , через 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
html lang="en"> head> meta charset="UTF-8"> title>database connections/title> /head> body> $username = "root"; $password = "pass"; $host = "localhost"; $connector = mysql_connect($host,$username,$password) or die("Unable to connect"); echo "Connections are made successfully::"; $selected = mysql_query("user_info", $connector) or die("Unable to connect"); //execute the SQL query and return records $result = mysql_query("SELECT * FROM users "); ?> table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;" > thead> tr> th>Id/th> th>User_info/th> th>Mail/th> th>Time_post/th> /tr> /thead> tbody> while( $row = mysql_fetch_array( $result) ){ echo " td>/td> td>/td> td>/td> td>/td> /tr>\n"; > ?> /tbody> /table> ($connector); ?> /body> /html>
Вывод HTML-таблицы с функцией сортировки на PHP + MySQL
Несколько примеров как вывести данные из БД в таблицу и добавить к ней возможность сортировки.
Итак, простой вывод таблицы и базы:
prepare("SELECT * FROM `tours` ORDER BY `hotel`"); $sth->execute(); $list = $sth->fetchAll(PDO::FETCH_ASSOC);
Вывод:
Заезд Отель Курорт Тип номера Питание Цена EUR
Результат:
Основной принцип пользовательской сортировки основан на GET параметрах, к ссылке в href добавляется параметр ?sort=xxx со значением текущей сортировки. PHP-скрипт его получает, проверяет и подставляет в SQL-запрос.
Далее рассмотрим его детально на нескольких примерах:
Сортировка в шапке таблицы
Заведем массив $sort_list с ключами и вариантами сортировки, чтобы упростить вывод ссылок заведем функцию sort_link_th() , которая будет их формировать исходя из значения переменной $_GET[‘sort’] .
'`date`', 'date_desc' => '`date` DESC', 'hotel_asc' => '`hotel`', 'hotel_desc' => '`hotel` DESC', 'city_asc' => '`city`', 'city_desc' => '`city` DESC', 'type_asc' => '`type`', 'type_desc' => '`type` DESC', 'food_asc' => '`food`', 'food_desc' => '`food` DESC', 'price_asc' => '`price`', 'price_desc' => '`price` DESC', ); /* Проверка GET-переменной */ $sort = @$_GET['sort']; if (array_key_exists($sort, $sort_list)) < $sort_sql = $sort_list[$sort]; >else < $sort_sql = reset($sort_list); >/* Запрос в БД */ $dbh = new PDO('mysql:dbname=db_name;host=localhost', 'логин', 'пароль'); $sth = $dbh->prepare("SELECT * FROM `tours` ORDER BY "); $sth->execute(); $list = $sth->fetchAll(PDO::FETCH_ASSOC); /* Функция вывода ссылок */ function sort_link_th($title, $a, $b) < $sort = @$_GET['sort']; if ($sort == $a) < return '' . $title . ' ▲'; > elseif ($sort == $b) < return '' . $title . ' ▼'; > else < return '' . $title . ''; > >
Вывод:
Результат:
Сортировка в виде списка
Преведущий код немного переделан:
'`date`', 'date_desc' => '`date` DESC', 'hotel_asc' => '`hotel`', 'hotel_desc' => '`hotel` DESC', 'city_asc' => '`city`', 'city_desc' => '`city` DESC', 'type_asc' => '`type`', 'type_desc' => '`type` DESC', 'food_asc' => '`food`', 'food_desc' => '`food` DESC', 'price_asc' => '`price`', 'price_desc' => '`price` DESC', ); /* Проверка GET-переменной */ $sort = @$_GET['sort']; if (array_key_exists($sort, $sort_list)) < $sort_sql = $sort_list[$sort]; >else < $sort_sql = reset($sort_list); >/* Запрос в БД */ $dbh = new PDO('mysql:dbname=db_name;host=localhost', 'логин', 'пароль'); $sth = $dbh->prepare("SELECT * FROM `tours` ORDER BY "); $sth->execute(); $list = $sth->fetchAll(PDO::FETCH_ASSOC); /* Функция вывода ссылок */ function sort_link_bar($title, $a, $b) < $sort = @$_GET['sort']; if ($sort == $a) < return '' . $title . ' ↑'; > elseif ($sort == $b) < return '' . $title . ' ↓'; > else < return '' . $title . ''; > >
Вывод:
Заезд Отель Курорт Тип номера Питание Цена EUR
Сортировка полем select
Во этом примере управление сортировкой будет производится с помощью , при его изменении отправляется форма c выбранным ключом сортировки .
'`date`', 'type' => '`type`', 'food' => '`food`', 'price_asc' => '`price`', 'price_desc' => '`price` DESC', ); /* Проверка GET-переменной */ $sort = @$_GET['sort']; if (array_key_exists($sort, $sort_list)) < $sort_sql = $sort_list[$sort]; >else < $sort_sql = reset($sort_list); >/* Запрос в БД */ $dbh = new PDO('mysql:dbname=db_name;host=localhost', 'логин', 'пароль'); $sth = $dbh->prepare("SELECT * FROM `tours` ORDER BY "); $sth->execute(); $list = $sth->fetchAll(PDO::FETCH_ASSOC);
Вывод:
Заезд Отель Курорт Тип номера Питание Цена EUR
Display Data in an HTML Table Using PHP & MySQL
Hello Developer, In this tutorial, You will learn to display data in an HTML table using PHP and MySQL. Even You will know more to fetch new records from the database and show them in the tabular format using MySQLi procedure, MySQLi Object-oriented, PDO & prepared statement with a new concept & an example.
![display data in HTML table using php mysql](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20837%20385'%3E%3C/svg%3E)
Steps to Display Data From MySQL Database with PHP
In this step, you will learn to display data from the database dynamically with an advanced coding concept that will help you to improve your coding skills for writing smart & standard code in PHP.
Before getting started, make sure that the local server (xamp/wamp) must be installed in your system and start it if it is not being started already.
Learn Also –
You can test yourself to display data with the following folder structure –
codingstatus/ |__database.php |__table.php |__developers.php |
1. Connect PHP to MySQL Database
You can use the following database connection query to connect PHP to the MySQL database
- $hostName – It contains host name
- $userName – It contains database username
- $password – It contains database password
- $databaseName – It contains database name.
connect_error) < die("Connection failed: " . $conn->connect_error); > ?>
2. Insert Data Into PHPMyAdmin Table
Before displaying data, you have to insert data into the Database. If you have not already done it and don’t know about it, then you can learn it through the following URL –
![insert data into phpmyadmin table](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20816%20212'%3E%3C/svg%3E)
3. Fetch Data From MySQL Table
Now, You have to fetch data from the MySQL table. So, just follow these points –
- First of all, include a database connection file database.php
- assign $conn to a new variable $db and table name to another variable $table
- Define columns name in an indexed array and assign them to the $columns
- Also, assign fetch_data() function to the $fetchData
fetch_data() – This function accepts three parameters like $db, $table & $column and It contains MySQLi SELECT query that will return records in an array format by fetching from the database
elseif (empty($columns) || !is_array($columns)) < $msg="columns Name must be defined in an indexed array"; >elseif(empty($tableName))< $msg= "Table Name is empty"; >else< $columnName = implode(", ", $columns); $query = "SELECT ".$columnName." FROM $tableName"." ORDER BY id DESC"; $result = $db->query($query); if($result== true)< if ($result->num_rows > 0) < $row= mysqli_fetch_all($result, MYSQLI_ASSOC); $msg= $row; >else < $msg= "No Data Found"; >>else < $msg= mysqli_error($db); >> return $msg; > ?>
4. Display Data in HTML Table
Now, You have to display data in the HTML table. So, you have to follow these points –
- First of all, Include PHP script file developers.php
- Create an HTML table using Bootsrap 4
- Check $fetchData is an array or not with if & else condition
- Then apply foreach loop to the $fetchData
- After that print the required data in the table
S.N Full Name Gender Email Mobile Number Address City State >else < ?> ?>
5. Test Yourself to insert data
After Implementing previous steps, You can test it yourself to open the following URL in your web browser
https://localhost/codingstatus/table.php
More Methods to display Data in HTML Table with PHP
Now, You should know more methods to display data in the database from the next step. After learning those methods, you can use one of them in your project.
From the next step, I have shared only the source code without a custom function. So that you can directly paste it into your project where you need to implement it.
Display Data using MySQLi Procedure
Display data with MySQLi Procedure
S.N Full Name Gender Email Mobile No Address City State 0) < $sn=1; while($data = mysqli_fetch_assoc($result)) < ?> > else < ?> No data found ?>
Display Data Using MySQLi Object-Oriented
Display data with MySQLi Object-Oriented
query($query); ?> S.N Full Name Gender Email Mobile No Address City State num_rows > 0) < $sn=1; while($data = $result->fetch_assoc()) < ?> > else < ?> No data found ?>
Display Data Using PDO
Connect Database with PDO
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); try < $query = "SELECT fullName, gender, email, mobile, address, city, state FROM developers"; $result = $conn->query($query); ?>
fetch(PDO::FETCH_ASSOC)) < ?> ?>
catch(PDOException $e) < echo "Error: " . $e->getMessage(); > Display Data Using Prepared Statement
Display data using Prepared Statement with MySQLi –
prepare($query); $prepared->execute(); $result = $prepared->get_result(); ?> S.N Full Name Gender Email Mobile No Address City State num_rows > 0) < $sn=1; while($data = $result->fetch_assoc()) < ?> > else < ?> No data found ?>
Display data using Prepared Statement with PDO –
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); try < $query = "SELECT fullName, gender, email, mobile, address, city, state FROM developers"; $prepared = $conn->prepare($query); $prepared->execute(); $result = $prepared -> fetchAll(PDO::FETCH_ASSOC); ?>
?>
catch(PDOException $e) < echo "Error: " . $e->getMessage(); > ?> Related posts: