Home Database Mysql Tutorial How to obtain record data from MySQL database in PHP

How to obtain record data from MySQL database in PHP

May 26, 2023 pm 08:52 PM
mysql php database

Get the total number of records in the data table

<?php
require &#39;linkConfig.php&#39;;//根据连接信息连接数据库
$sql = "select count(*) from druserlist where C04=&#39;普通用户&#39;";//查询数据表
$result = $mysqli->query($sql);//以索引的方式返回一个结果集
list($rowCount)=$result->fetch_row();
echo &#39;记录总数:&#39;.$rowCount;
$result->close();
$mysqli->close();
?>
Copy after login

It can also be obtained like this:

<?php
require &#39;linkConfig.php&#39;;//根据连接信息连接数据库
$sql = "select count(*) from druserlist where C04=&#39;普通用户&#39;";//查询数据表
$result = $mysqli->query($sql);//以索引的方式返回一个结果集
$row = $result->fetch_row();
echo &#39;记录总数:&#39;.$row[0];
$result->close();
$mysqli->close();
?>
Copy after login

Other forms: ($row['total'] replaced by $ row[0] can also be used)

<?php
require &#39;linkConfig.php&#39;;//根据连接信息连接数据库
$sql = "select count(*) as total from druserlist where C04=&#39;普通用户&#39;";//查询数据表
$result = $mysqli->query($sql);//以索引的方式返回一个结果集
$row = $result->fetch_array(MYSQLI_BOTH);
echo &#39;记录总数:&#39;.$row[&#39;total&#39;];
$result->close();
$mysqli->close();
?>
Copy after login

I checked the PHP operation manual and found that there are too many similar functions, which means that PHP has many processing methods for the same needs.

Get the records of the database query table and return it in JSON format

<?php
$sql = "select * from druserlist";//查询语句
$res = $mysqli->query($sql);//执行查询
$result = array();//准备一个空数组
while ($row = $res->fetch_assoc()){
    //对结果集进行逐行取值并压入到数组中
    array_push($result,$row);
}
echo json_encode($result);//返回前端JSON格式数据
?>
Copy after login

Returned data:

[
  {
    "C01": "00924001",
    "C02": "经理办01",
    "C03": "1",
    "C04": "普通用户",
    "C05": "1"
  },
  {
    "C01": "00924002",
    "C02": "经理办02",
    "C03": "2",
    "C04": "普通用户",
    "C05": "1"
  },
  {
    "C01": "00923128",
    "C02": "人事科01",
    "C03": "1",
    "C04": "普通用户",
    "C05": "人事科的张小勇"
  }
]
Copy after login

Get the paging record data of the data table and return it in JSON format (Take LayUI's paging data as an example)

<?php
$page  = isset($_POST[&#39;page&#39;]) ? intval($_POST[&#39;page&#39;]) : 1;//获取页数
$limit = isset($_POST[&#39;limit&#39;]) ? intval($_POST[&#39;limit&#39;]) : 10;//获取每页的显示记录数
$offset = ($page-1)*$limit;//计算起始位置
 
require &#39;linkConfig.php&#39;;//连接数据库
$sql1 = "select count(*) from druserlist";
$result1 = $mysqli->query($sql1);
$rowCount = $result1->fetch_row();
 
$returnArr[&#39;code&#39;]=0;
$returnArr[&#39;msg&#39;]="";
$returnArr[&#39;count&#39;]=$rowCount[0];//总记录数
 
$sql2 = "select * from druserlist order by C01 limit $offset,$limit";
$res = $mysqli->query($sql2);
$result = array();
while ($row = $res->fetch_assoc()){
    array_push($result,$row);
}
$returnArr[&#39;data&#39;]=$result;
echo json_encode($returnArr);//返回JSON格式数据
$res->free();
$mysqli->close();
?>
Copy after login

Returned data:

{
  "code": 0,
  "msg": "",
  "count": "12",
  "data": [
    {
      "C01": "00101078",
      "C02": "HaoR",
      "C03": "2",
      "C04": "管理员",
      "C05": "1"
    },
    {
      "C01": "00323007",
      "C02": "研究中心01",
      "C03": "1",
      "C04": "管理员",
      "C05": "1"
    },
    {
      "C01": "00616001",
      "C02": "财务科01",
      "C03": "1",
      "C04": "管理员",
      "C05": "1"
    },
    {
      "C01": "00616002",
      "C02": "财务科02",
      "C03": "1",
      "C04": "管理员",
      "C05": "1"
    },
    {
      "C01": "00616003",
      "C02": "财务科03",
      "C03": "1",
      "C04": "管理员",
      "C05": "1"
    },
    {
      "C01": "00923127",
      "C02": "admin",
      "C03": "1",
      "C04": "管理员",
      "C05": "系统管理员"
    },
    {
      "C01": "00923128",
      "C02": "人事科01",
      "C03": "1",
      "C04": "普通用户",
      "C05": "人事科的张小勇"
    },
    {
      "C01": "00923129",
      "C02": "人事科02",
      "C03": "1",
      "C04": "管理员",
      "C05": "1"
    }
  ]
}
Copy after login

can return different data styles according to the front-end paging requirements. Once you know the PHP processing, it will be easier to handle. .

PHP’s processing of mysql database query result set.

⑴ fetch_array()

<?php
require &#39;linkConfig.php&#39;;//根据连接信息连接数据库
$sql = "select C01,C02 from druserlist where C04=&#39;普通用户&#39;";//查询数据表
$result=$mysqli->query($sql);//以索引的方式返回一个结果集
while($row = $result->fetch_array()){
    $rows[] = $row;
}
foreach($rows as $row){
    echo $row[&#39;C01&#39;].&#39;  &#39;.$row[&#39;C02&#39;].&#39;<br>&#39;;
}
$result->close();
$mysqli->close();
?>
Copy after login

Results returned line by line:

00924001 Manager Office 01
00924002 Manager Office 02
00923128 Personnel Department 01

Return JSON format:

<?php
require &#39;linkConfig.php&#39;;//根据连接信息连接数据库
$sql = "select C01,C02 from druserlist where C04=&#39;普通用户&#39;";//查询数据表
$result=$mysqli->query($sql);//以索引的方式返回一个结果集
while($row = $result->fetch_array()){
    $rows[] = $row;
}
echo json_encode($rows);//返回JSON格式数据
$result->close();
$mysqli->close();
?>
Copy after login

Returned results:

[
  {
    "0": "00924001",
    "1": "经理办01",
    "C01": "00924001",
    "C02": "经理办01"
  },
  {
    "0": "00924002",
    "1": "经理办02",
    "C01": "00924002",
    "C02": "经理办02"
  },
  {
    "0": "00923128",
    "1": "人事科01",
    "C01": "00923128",
    "C02": "人事科01"
  }
]
Copy after login

It can be seen from the above output that the output is in the form of numbers and field names. According to the PHP operation manual, you can get the record value by giving the parameters of the fetch_array() function, that is, the following three outputs are the same.

<?php
require &#39;linkConfig.php&#39;;//根据连接信息连接数据库
$sql = "select C01,C02 from druserlist where C04=&#39;普通用户&#39;";//查询数据表
$result=$mysqli->query($sql);//以索引的方式返回一个结果集
//第一种输出
while($row = mysqli_fetch_array($result, MYSQLI_NUM)){
    echo $row[0].&#39;  &#39;.$row[1].&#39;<br>&#39;;
}
//第二种输出
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
    echo $row[&#39;C01&#39;].&#39;  &#39;.$row[&#39;C02&#39;].&#39;<br>&#39;;
}
//第三种输出
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
    echo $row[0].&#39;  &#39;.$row[&#39;C02&#39;].&#39;<br>&#39;;
}
$result->close();
$mysqli->close();
?>
Copy after login

The three outputs are the following results:

00924001 Manager Office 01
00924002 Manager Office 02
00923128 Personnel Department 01

⑵ fetch_row()

The above output can be performed using the following method:

<?php
require &#39;linkConfig.php&#39;;//根据连接信息连接数据库
$sql = "select C01,C02 from druserlist where C04=&#39;普通用户&#39;";//查询数据表
$result=$mysqli->query($sql);//以索引的方式返回一个结果集
while ($row = $result->fetch_row()) {
    printf ("%s %s <br>", $row[0], $row[1]);
}
$result->close();
$mysqli->close();
?>
Copy after login

⑶fetch_assoc()

The above output can be performed using the following method :

<?php
require &#39;linkConfig.php&#39;;//根据连接信息连接数据库
$sql = "select C01,C02 from druserlist where C04=&#39;普通用户&#39;";//查询数据表
$result=$mysqli->query($sql);//以索引的方式返回一个结果集
while ($row = $result->fetch_assoc()) {
    printf ("%s %s <br>", $row["C01"], $row["C02"]);
}
$result->close();
$mysqli->close();
?>
Copy after login

⑷ fetch_all()

Similar to fetch_array, there are parameter selections, namely: MYSQLI_ASSOC, MYSQLI_NUM or MYSQLI_BOTH. The default is MYSQLI_BOTH.

<?php
require &#39;linkConfig.php&#39;;//根据连接信息连接数据库
$sql = "select C01,C02 from druserlist where C04=&#39;普通用户&#39;";//查询数据表
$result=$mysqli->query($sql);//以索引的方式返回一个结果集
$rows=$result->fetch_all(MYSQLI_NUM);
$r=0;
while ( $r < mysqli_num_rows($result) ) {
    printf ("%s %s <br>", $rows[$r][0], $rows[$r][1]);
    $r++;
}
$result->close();
$mysqli->close();
?>
Copy after login
<?php
require &#39;linkConfig.php&#39;;//根据连接信息连接数据库
$sql = "select C01,C02 from druserlist where C04=&#39;普通用户&#39;";//查询数据表
$result=$mysqli->query($sql);//以索引的方式返回一个结果集
$rows=$result->fetch_all(MYSQLI_ASSOC);
$r=0;
while ( $r < mysqli_num_rows($result) ) {
    printf ("%s %s <br>", $rows[$r][&#39;C01&#39;], $rows[$r][&#39;C02&#39;]);
    $r++;
}
$result->close();
$mysqli->close();
?>
Copy after login
<?php
require &#39;linkConfig.php&#39;;//根据连接信息连接数据库
$sql = "select C01,C02 from druserlist where C04=&#39;普通用户&#39;";//查询数据表
$result=$mysqli->query($sql);//以索引的方式返回一个结果集
$rows=$result->fetch_all(MYSQLI_BOTH);
$r=0;
while ( $r < mysqli_num_rows($result) ) {
    printf ("%s %s <br>", $rows[$r][0], $rows[$r][&#39;C02&#39;]);
    $r++;
}
$result->close();
$mysqli->close();
?>
Copy after login

The output of the above three pieces of code is the same.

The above is the detailed content of How to obtain record data from MySQL database in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
MySQL: The Database, phpMyAdmin: The Management Interface MySQL: The Database, phpMyAdmin: The Management Interface Apr 29, 2025 am 12:44 AM

MySQL and phpMyAdmin can be effectively managed through the following steps: 1. Create and delete database: Just click in phpMyAdmin to complete. 2. Manage tables: You can create tables, modify structures, and add indexes. 3. Data operation: Supports inserting, updating, deleting data and executing SQL queries. 4. Import and export data: Supports SQL, CSV, XML and other formats. 5. Optimization and monitoring: Use the OPTIMIZETABLE command to optimize tables and use query analyzers and monitoring tools to solve performance problems.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

Steps to add and delete fields to MySQL tables Steps to add and delete fields to MySQL tables Apr 29, 2025 pm 04:15 PM

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.

What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

How to uninstall MySQL and clean residual files How to uninstall MySQL and clean residual files Apr 29, 2025 pm 04:03 PM

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

An efficient way to batch insert data in MySQL An efficient way to batch insert data in MySQL Apr 29, 2025 pm 04:18 PM

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

How to configure the character set and collation rules of MySQL How to configure the character set and collation rules of MySQL Apr 29, 2025 pm 04:06 PM

Methods for configuring character sets and collations in MySQL include: 1. Setting the character sets and collations at the server level: SETNAMES'utf8'; SETCHARACTERSETutf8; SETCOLLATION_CONNECTION='utf8_general_ci'; 2. Create a database that uses specific character sets and collations: CREATEDATABASEexample_dbCHARACTERSETutf8COLLATEutf8_general_ci; 3. Specify character sets and collations when creating a table: CREATETABLEexample_table(idINT

See all articles