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 mmo能不能做客户端怪物
  • ¥15 osm下载到arcgis出错
  • ¥15 Dell g15 每次打开eiq portal后3分钟内自动退出
  • ¥200 使用python编写程序,采用socket方式获取网页实时刷新的数据,能定时print()出来就行。
  • ¥15 matlab如何根据图片中的公式绘制e和v的曲线图
  • ¥15 我想用Python(Django)+Vue搭建一个用户登录界面,但是在运行npm run serve时报错了如何解决?
  • ¥15 QQ邮箱过期怎么恢复?
  • ¥15 登录他人的vue项目显示服务器错误
  • ¥15 (标签-android|关键词-app)
  • ¥15 comsol仿真压阻传感器