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 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 github训练的模型参数无法下载
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题