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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看