Home Backend Development PHP Tutorial Commonly used functions for obtaining SQL query results in PHP (detailed examples)

Commonly used functions for obtaining SQL query results in PHP (detailed examples)

Oct 27, 2021 pm 05:03 PM
mysql php

In the previous article, I brought you "Usage of mysqli_select_db and mysqli_query functions in PHP", which gave you a detailed introduction to how to use the two functions and their main functions. In this article, we continue to look at how to obtain SQL query results in PHP. I hope everyone has to help!

Commonly used functions for obtaining SQL query results in PHP (detailed examples)

In the previous article, we talked about how to execute a SQL statement, which is to call the mysqli_query() function. Through this function we can already The database information has been queried, but in our daily development we still need to process the result to get the information we want. Next, let’s take a look at several functions commonly used to process results in PHP.

<strong><span style="font-size: 20px;">mysqli_fetch_row()</span></strong> function

mysqli_fetch_row() function You can get a row from the result set and return it in the form of an index array. The syntax format is as follows:

mysqli_result::fetch_row()
Copy after login

This is object-oriented writing, and the process-oriented writing is as follows:

mysqli_fetch_row(mysqli_result $result)
Copy after login

You need to pay attention to it are: mysqli_result and $result are represented as the result set obtained using the mysqli_query() function.

Next let’s take a look at the usage of the mysqli_fetch_row() function through an example. The example is as follows:

<?php
    $host     = &#39;localhost&#39;;
    $username = &#39;root&#39;;
    $password = &#39;root&#39;;
    $dbname   = &#39;test&#39;;
    $mysql    = new Mysqli($host, $username, $password, $dbname);
    if($mysql -> connect_errno){
        die(&#39;数据库连接失败:&#39;.$mysql->connect_errno);
    }else{
        $sql    = &#39;select name,sex,age from user&#39;;     // SQL 语句
        $result = $mysql -> query($sql);               // 执行上面的 SQL 语句
        $data   = $result -> fetch_row();
        $mysql -> close();
    }
    echo &#39;<pre class="brush:php;toolbar:false">&#39;;
    print_r($data);
?>
Copy after login

Output result:

Commonly used functions for obtaining SQL query results in PHP (detailed examples)

In the above example, one row of data in the database is successfully queried through the mysqli_fetch_row() function, and is returned in the form of an index array. Then let's take a look at the different return forms.

<strong><span style="max-width:90%">mysqli_fetch_assoc()</span></strong> function

mysqli_fetch_assoc() function You can get a row from the result set and return it in the form of an associative array. The syntax format of this function is as follows:

mysqli_result::fetch_assoc()
Copy after login

This is its object-oriented syntax format, and the following is its procedural-oriented syntax format:

mysqli_fetch_assoc(mysqli_result $result)
Copy after login

It should be noted that: mysqli_result and $result are represented as result sets obtained using the mysqli_query() function.

Next let’s look at the use of the mysqli_fetch_assoc() function through an example. The example is as follows:

<?php
    $host     = &#39;localhost&#39;;
    $username = &#39;root&#39;;
    $password = &#39;root&#39;;
    $dbname   = &#39;test&#39;;
    $link     = @mysqli_connect($host, $username, $password, $dbname);
    if($link){
        $sql    = &#39;select name,sex,age from user&#39;;  // SQL 语句
        $result = mysqli_query($link, $sql);        // 执行 SQL 语句,并返回结果
        $data   = mysqli_fetch_assoc($result);      // 从结果集中获取一条数据
        mysqli_close($link);
    }else{
        echo &#39;数据库连接失败!&#39;;
    }
    echo &#39;<pre class="brush:php;toolbar:false">&#39;;
    print_r($data);
?>
Copy after login

Output result:

Commonly used functions for obtaining SQL query results in PHP (detailed examples)

From the above example, we successfully obtained a row of information in the database through the mysqli_fetch_assoc() function and returned it through an associative array. We can also control the form of the returned data through a function, so that it can be an index array, an associative array, or a combination of both. In this case, we will use the mysqli_fetch_array() function.

<strong><span style="max-width:90%">mysqli_fetch_array()</span></strong> function

mysqli_fetch_array() function You can get a row from the result set and return it in the form of an associative array, an index array, or both according to the parameters. Its syntax format is as follows:

mysqli_result::fetch_array([int $resulttype = MYSQLI_BOTH])
Copy after login

This is an object-oriented syntax, and the following is process-oriented The syntax:

mysqli_fetch_array(mysqli_result $result[, int $resulttype = MYSQLI_BOTH])
Copy after login

It should be noted that:

  • ##mysqli_result and $result are expressed as The result set obtained using the mysqli_query() function.

  • $resulttype is an optional parameter. It is a constant used to set the type of return value. Its value can be MYSQLI_ASSOC, MYSQLI_NUM or MYSQLI_BOTH indicates different types of return values.

Next let’s take a look at the usage of the mysqli_fetch_array() function through an example. The example is as follows:

<?php
    $host     = &#39;localhost&#39;;
    $username = &#39;root&#39;;
    $password = &#39;root&#39;;
    $dbname   = &#39;test&#39;;
    $link     = @mysqli_connect($host, $username, $password, $dbname);
    if($link){
        $sql    = &#39;select name,sex,age from user&#39;;          // SQL 语句
        $result = mysqli_query($link, $sql);                // 执行 SQL 语句,并返回结果
        $data   = mysqli_fetch_array($result, MYSQLI_ASSOC);// 从结果集中获取所有数据
        mysqli_close($link);
    }else{
        echo &#39;数据库连接失败!&#39;;
    }
    echo &#39;<pre class="brush:php;toolbar:false">&#39;;
    print_r($data);
?>
Copy after login

Output result:


Commonly used functions for obtaining SQL query results in PHP (detailed examples)

In the above example, we chose to return data in the form of an associative array. We can choose different types of return values ​​through the mysqli_fetch_array() function.

<strong>mysqli_fetch_all() <span style="max-width:90%"></span></strong>Function

mysqli_fetch_all() function You can get all the data in the result set and return it in the form of an associative array, an index array, or both according to the parameters. Its syntax format is as follows:

mysqli_result::fetch_all([int $resulttype = MYSQLI_NUM])
Copy after login

This is object-oriented writing, and the following is process-oriented The writing method:

mysqli_fetch_all(mysqli_result $result [, int $resulttype = MYSQLI_NUM])
Copy after login

It should be noted that: the syntax is the same as the mysqli_fetch_array() function

  • ##mysqli_resul

    t and $result Represented as a result set obtained using the mysqli_query() function. </li><li><p><code>$resulttype 为可选参数,它是一个常量,用来设定返回值的类型,它的取值可以是 MYSQLI_ASSOCMYSQLI_NUM MYSQLI_BOTH表示返回值的不同类型。

接下来通过示例来看一下mysqli_fetch_all() 函数的使用,示例如下:

<?php
    $host     = &#39;localhost&#39;;
    $username = &#39;root&#39;;
    $password = &#39;root&#39;;
    $dbname   = &#39;test&#39;;
    $mysql    = new Mysqli($host, $username, $password, $dbname);
    if($mysql -> connect_errno){
        die(&#39;数据库连接失败:&#39;.$mysql->connect_errno);
    }else{
        $sql    = &#39;select name,sex,age from user&#39;;     // SQL 语句
        $result = $mysql -> query($sql);               // 执行上面的 SQL 语句
        $data   = $result -> fetch_all(MYSQLI_ASSOC);
        $mysql -> close();
    }
    echo &#39;<pre class="brush:php;toolbar:false">&#39;;
    print_r($data);
?>
Copy after login

输出结果:

Commonly used functions for obtaining SQL query results in PHP (detailed examples)

上述示例中,便是通过mysqli_fetch_all() 函数选择以关联数组的形式返回所有的数据。

大家如果感兴趣的话,可以点击《PHP视频教程》进行更多关于PHP知识的学习。

The above is the detailed content of Commonly used functions for obtaining SQL query results in PHP (detailed examples). 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
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 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
1670
14
PHP Tutorial
1276
29
C# Tutorial
1256
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.

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.

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.

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.

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.

Detailed explanation of the installation steps of MySQL on macOS system Detailed explanation of the installation steps of MySQL on macOS system Apr 29, 2025 pm 03:36 PM

Installing MySQL on macOS can be achieved through the following steps: 1. Install Homebrew, using the command /bin/bash-c"$(curl-fsSLhttps://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)". 2. Update Homebrew and use brewupdate. 3. Install MySQL and use brewinstallmysql. 4. Start MySQL service and use brewservicesstartmysql. After installation, you can use mysql-u

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.

Composer: The Package Manager for PHP Developers Composer: The Package Manager for PHP Developers May 02, 2025 am 12:23 AM

Composer is a dependency management tool for PHP, and manages project dependencies through composer.json file. 1) parse composer.json to obtain dependency information; 2) parse dependencies to form a dependency tree; 3) download and install dependencies from Packagist to the vendor directory; 4) generate composer.lock file to lock the dependency version to ensure team consistency and project maintainability.

See all articles