douwaif22244 2012-05-29 23:46
浏览 92
已采纳

以JSON格式存储多个记录时出错

I've problem with my code, the reason, when run query un PHP FILE, this retrieve all records from SELECT * FROM material, then it pass to JS FILE for process and store all records in an array json format, but display this error:

Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result 
resource in C:\AppServ\www\biblioteca\include\doLogin.php on line 31 []

_

PHP FILE WITH FUNCTIONS

.........
public function searchMat($tipoBusqueda,$terminoBuscar){

$query = " SELECT * FROM material ";
$result = mysql_query($query) or die (mysql_error());
$resultArray =  mysql_fetch_assoc($result);
return $resultArray;
}

OTHER PHP FILE with functions

$results = $db->searchMat($tipoBusqueda, $terminoBuscar);
$jsonSearchResults = array();

if ($results != false) {
    while($row = mysql_fetch_assoc($results)) {
        $jsonSearchResults = array (
        'clavemat' => $row['cve_mat'],
        'tipomat' => $row['tipo_mat'],
        'titulomat' => $row['titulo_mat'],
        'autormat' => $row['autor_mat'],
        'editmat' => $row['edit_mat'],
        'success' => 'success', 
        );  
    }

    echo json_encode($jsonSearchResults);
} 

EDIT:

  • 写回答

3条回答 默认 最新

  • dsieyx2015 2012-05-29 23:58
    关注

    You're calling mysql_fetch_assoc two times. The first time on the resource you got from mysql_query, the second time on an array - invalid.

    Also, when you would loop over all rows, you need to add to $jsonSearchResults. As @RezaSanaie already said, it gets overwritten each iteration in your code. It should be:

    public function searchMat() {
    /* returns the material table as a resource */
        $query = "SELECT * FROM material";
        $result = mysql_query($query) or die (mysql_error());
        return $result;
    }
    
    $results = $db->searchMat();
    $jsonSearchResults = array();
    while ($results!=false && $row = mysql_fetch_assoc($results)) {
        array_push($jsonSearchResults, array(
            'clavemat' => $row['cve_mat'],
            'tipomat' => $row['tipo_mat'],
            'titulomat' => $row['titulo_mat'],
            'autormat' => $row['autor_mat'],
            'editmat' => $row['edit_mat'],
            'success' => 'success'
        ));
    }   
    echo json_encode($jsonSearchResults);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 网络科学导论,网络控制
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)