当前位置:网站首页>PHP MySQL reads data
PHP MySQL reads data
2022-07-03 17:51:00 【Crooning ~ shallow singing】
from MySQL Database reads data
SELECT Statement is used to read data from a data table :
SELECT column_name(s) FROM table_name
We can use * Number to read all the fields in the data table :
SELECT * FROM table_name
To learn more about SQL Knowledge , Please visit our SQL course .
Use MySQLi
In the following example, we start from myDB Database MyGuests Table read id, firstname and lastname Column and display it on the page :
example (MySQLi - object-oriented )
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die(" The connection fails : " . $conn->connect_error); } $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = $conn->query($sql); if ($result->num_rows > 0) { // Output data while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; } } else { echo "0 result "; } $conn->close(); ?>
The above code is parsed as follows :
First , We set it up SQL Statements from MyGuests Read in data table id, firstname and lastname Three fields . Then we use this SQL Statement takes the result set from the database and assigns it to the copied variable $result.
function num_rows() Judge the returned data .
If multiple pieces of data are returned , function fetch_assoc() Put the associative set into the associative array and output circularly . while() Loop out the result set , And the output id, firstname and lastname Three field values .
The following example uses MySQLi Process oriented approach , The effect is similar to the above code :
example (MySQLi - Process oriented )
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die(" The connection fails : " . mysqli_connect_error()); } $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { // Output data while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; } } else { echo "0 result "; } mysqli_close($conn); ?>
Use PDO (+ Preprocessing )
The following example uses preprocessing statements .
Selected MyGuests In the table id, firstname and lastname Field , And on the HTML In the table :
example (PDO)
<?php echo "<table style='border: solid 1px black;'>"; echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>"; class TableRows extends RecursiveIteratorIterator { function __construct($it) { parent::__construct($it, self::LEAVES_ONLY); } function current() { return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>"; } function beginChildren() { echo "<tr>"; } function endChildren() { echo "</tr>" . "\n"; } } $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests"); $stmt->execute(); // Set the result set to an associative array $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { echo $v; } } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } $conn = null; echo "</table>"; ?>
边栏推荐
- Automata and automatic line of non-standard design
- Embedded-c language-7
- 国内如何购买Google Colab会员
- 基于人脸识别的课堂考勤系统 tkinter+openpyxl+face_recognition
- Basic grammar of interview (Part 2)
- AcWing 3438. Number system conversion
- Supervisor monitors gearman tasks
- [set theory] order relation: summary (partial order relation | partial order set | comparable | strictly less than | covering | hasto | total order relation | quasi order relation | partial order rela
- Tensorboard quick start (pytoch uses tensorboard)
- POM in idea XML graying solution
猜你喜欢
The third day of writing C language by Yabo people
Classroom attendance system based on face recognition tkinter+openpyxl+face_ recognition
Analysis report on production and marketing demand and investment forecast of China's PVC industry from 2021 to 2026
QT learning diary 9 - dialog box
Investigation on the operation prospect of the global and Chinese Anti enkephalinase market and analysis report on the investment strategy of the 14th five year plan 2022-2028
Tensorboard quick start (pytoch uses tensorboard)
互聯網醫院HIS管理平臺源碼,在線問診,預約掛號 智慧醫院小程序源碼
互联网医院HIS管理平台源码,在线问诊,预约挂号 智慧医院小程序源码
聊聊支付流程的设计与实现逻辑
Implementation of Tetris in C language
随机推荐
[combinatorics] recursive equation (special solution form | special solution solving method | special solution example)
A. Odd Selection【BruteForce】
Classroom attendance system based on face recognition tkinter+openpyxl+face_ recognition
Brief introduction to the core functions of automatic penetration testing tool
Kotlin的协程:上下文
PUT vs. POST for Uploading Files - RESTful API to be Built Using Zend Framework
聊聊支付流程的设计与实现逻辑
Analysis report on production and marketing demand and investment forecast of China's PVC industry from 2021 to 2026
Golang单元测试、Mock测试以及基准测试
Loop through JSON object list
Notes on problems -- watching videos on edge will make the screen green
QT adjust win screen brightness and sound size
Baiwen.com 7 days Internet of things smart home learning experience punch in the next day
Kotlin的協程:上下文
Internet hospital his management platform source code, online consultation, appointment registration smart hospital applet source code
AcWing 4489. Longest subsequence
Design limitations of structure type (struct)
Where is the database account used when running SQL tasks in data warehouse tasks configured
The third day of writing C language by Yabo people
Tensorboard quick start (pytoch uses tensorboard)