search
HomeBackend DevelopmentPHP TutorialCommonly used functions for obtaining SQL query results in PHP (detailed examples)

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()

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

mysqli_fetch_row(mysqli_result $result)

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);
?>

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="font-size: 20px;">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()

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

mysqli_fetch_assoc(mysqli_result $result)

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);
?>

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="font-size: 20px;">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])

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

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

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);
?>

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="font-size: 20px;"></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])

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

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

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.

  • $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);
?>

输出结果:

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
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor