You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PHP从MySQL数据库获取全部指定条件的数据

解决PHP从MySQL获取多条符合条件记录的问题

问题说明

需要从MySQL数据库中获取全部符合条件的记录,但当前代码仅能返回单条记录,无法读取多条匹配数据。

原代码问题点

原getMailByNikRequest函数中,使用fetch_assoc()方法仅会返回结果集中的第一行数据,因此无法获取所有匹配的记录。

修改方案

1. 修正数据查询函数

修改getMailByNikRequest函数,通过循环遍历结果集,将所有记录存入数组后返回:

public function getMailByNikRequest($nik_request){
    $stmt = $this->con->prepare("SELECT * FROM surat_request WHERE nik_request = ?");
    $stmt->bind_param("s",$nik_request);
    $stmt->execute();
    $result = $stmt->get_result();
    $mails = [];
    // 循环读取所有行数据
    while ($row = $result->fetch_assoc()) {
        $mails[] = $row;
    }
    return $mails;
}

2. 调整响应输出逻辑

修改业务处理代码,将多条记录以数组形式返回:

<?php
include '../includes/DbOperations.php';
$response = array();

if($_SERVER['REQUEST_METHOD']=='POST'){
    if(isset($_POST['nik_request'])) {
        $db = new DbOperations();
        $mails = $db->getMailByNikRequest($_POST['nik_request']);
        
        if(!empty($mails)){
            $response['error'] = false;
            $response['mails'] = $mails; // 存储所有符合条件的记录
        }else{
            $response['error'] = true;
            $response['message'] = "Not Found";
        }
    }
}else{
    $response['error'] = true;
    $response['message'] = "Invalid Request";
}

echo json_encode($response);

3. 可选优化:移除冗余函数

原readMail函数用于判断是否存在记录,现在可以直接通过判断返回的$mails数组是否为空来替代,减少一次重复的数据库查询,无需保留该函数。

内容的提问来源于stack exchange,提问作者MuhammadAl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 21:05:19