当前位置:网站首页>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>"; ?>
边栏推荐
- PHP processing - watermark images (text, etc.)
- Assembly for unloading Loadfrom() loaded assembly - unloading the assembly loaded with assembly LoadFrom()
- Baiwen.com 7 days Internet of things smart home learning experience punch in the next day
- Golang单元测试、Mock测试以及基准测试
- 1146_ SiCp learning notes_ exponentiation
- How to purchase Google colab members in China
- PHP returns 500 errors but no error log - PHP return 500 error but no error log
- SDNUOJ1015
- Is AI too slow to design pictures and draw illustrations? 3 sets of practical brushes to save you
- UE4 official charging resources, with a total price of several thousand
猜你喜欢
![How to read the source code [debug and observe the source code]](/img/40/a2fca67bcde3c468a739c6990325f4.jpg)
How to read the source code [debug and observe the source code]

Embedded-c language-7

Internet Hospital his Management Platform source, online Inquiry, appointment Registration Smart Hospital Small program source

Internet hospital his management platform source code, online consultation, appointment registration smart hospital applet source code

Global and Chinese health care OEM and ODM market status survey and investment planning recommendations report 2022-2028

Global and Chinese pediatric palliative care drug market development research and investment planning recommendations report 2022-2028

互联网医院HIS管理平台源码,在线问诊,预约挂号 智慧医院小程序源码

Introduction to SolidWorks gear design software tool geartrax

Ml (machine learning) softmax function to realize the classification of simple movie categories

POM in idea XML graying solution
随机推荐
Discussion sur la logique de conception et de mise en oeuvre du processus de paiement
Applet with multiple tabs and Swipers + paging of each tab
c# .net 工具生态
c# . Net tool ecosystem
Loop through JSON object list
Research Report on investment trends and development planning of China's thermal insulation material industry, 2022-2028
link preload prefetch
一入“远程”终不悔,几人欢喜几人愁。| 社区征文
鸿蒙第四次培训
Type conversion, variable
自动渗透测试工具核心功能简述
AcWing 3438. Number system conversion
Graduation summary
ArrayList analysis 3: delete elements
Kotlin的协程:上下文
List of financial products in 2022
[combinatorics] recursive equation (special solution example 1 Hannover tower complete solution process | special solution example 2 special solution processing when the characteristic root is 1)
Design limitations of structure type (struct)
[vscode] convert tabs to spaces
i++与++i的区别:通俗易懂的讲述他们的区别