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 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题