PDO:执行数据库更新时,Json无法呈现响应

时间:2019-01-01 22:35:35

标签: php mysql json pdo

当他查看页面时,我想在数据库字段中注册当前登录的用户名。数据库是MySQL,语言是PHP(XAMPP本地服务器)

这是我正在使用的代码:

$ActiveUser = USER_NAME;
$id         = $rec_id;
$db->rawQuery("UPDATE postagens SET post_user_posted='$ActiveUser' WHERE 
post_id='$id'");

当我通过Web浏览器打开页面时,数据库已成功更新。但是,尽管数据库已正确更新,但是该页面返回以下错误消息:

  

!错误处理   请求。

这时,页面应该获得数据库信息并显示。但是,每当出现以上错误时,该页面就不会从数据库中加载信息。该页面仅显示错误消息,并且字段为空白。

我认为json渲染一定发生了一些事情。如果删除UPDATE查询代码,则不会显示错误,并且数据库信息也会正确显示。还要删除json返回的代码:

{"post_id":"1","post_title":"My first post.","post_text":"Lorem ipsum
dollor.","post_date":"2018-12-31
12:00:00","post_user_posted":"Welisson"}

当我运行更新查询时,json不会返回(或返回空)

错误日志显示如下:

PHP Fatal error:  Uncaught PDOException: SQLSTATE[HY000]: General 
    error 
    in C:\xampp\htdocs\projetosimples\app\models\PDODb.php:680
    Stack trace:
    0 C:\xampp\htdocs\projetosimples\app\models\PDODb.php(680): 
    PDOStatement- 
    >fetchAll(2)
    1 C:\xampp\htdocs\projetosimples\app\models\PDODb.php(1611): PDODb- 
    >buildResult(Object(PDOStatement)) 2 C:\xampp\htdocs\projetosimples\app\controllers\PostagensController.php(93): PDODb->rawQuery('UPDATE postagen...')
    3 C:\xampp\htdocs\projetosimples\system\Router.php(227): PostagensController->view('1')
    4 C:\xampp\htdocs\projetosimples\system\Router.php(92): Router->run('postagens/view/...')
    5 C:\xampp\htdocs\projetosimples\index.php(84): Router->init()
    6 {main}
      thrown in C:\xampp\htdocs\projetosimples\app\models\PDODb.php on line 680

PDODb.php大约680行:

/**
     * Return query result
     * 
     * @param PDOStatement $stmt
     * @return array
     */
    private function buildResult($stmt)
    {
        if ($this->useGenerator) {
            return $this->buildResultGenerator($stmt);
        } else {
            return $stmt->fetchAll($this->returnType); //THIS IS THE LINE 680
        }
    }

PDODb.php 1611年左右的行:

/**
     * Perform db query
     * 
     * @param string $query
     * @param array $params
     * @return array
     */
    public function rawQuery($query, $params = null)
    {
        $this->query = $query;
        if (is_array($params)) {
            $this->params = $params;
        }
        $stmt = $this->prepare();
        if ($stmt) {
            $stmt->execute();
            $this->lastError     = $stmt->errorInfo();
            $this->lastErrorCode = $stmt->errorCode();
            $result              = $this->buildResult($stmt); //LINE 1611
        } else {
            $result = null;
        }
        $this->reset();
        return $result;
    }

PostagensController.php第93行:

 function view( $rec_id = null , $value = null){
            $db = $this->GetModel();
            $fields = array( 'post_id',     'post_title',   'post_text',    'post_date',    'post_user_posted' );
            if( !empty($value) ){
                $db->where($rec_id, urldecode($value));
            }
            else{
                $db->where('post_id' , $rec_id);
            }
            $record = $db->getOne( 'postagens', $fields );
            if(!empty($record)){
                $ActiveUser = ucwords(USER_NAME);
    $id         = $rec_id;
                render_json($record); //THIS IS THE LINE 93
            }
            else{
                if($db->getLastError()){
                    render_error($db->getLastError());
                }
                else{
                    render_error("Registro não encontrado",404);
                }
            }
        }

Router.php第227行:

        // use the force layout when force layout is set
        $controller->view->force_layout = $this->force_layout;


        // Initialize Controller Class And Pass All Arguments to the Controller Action
        call_user_func_array(array($controller,$action),$args); //LINE 227
    }
    else{
        if($this->is_partial_view==true){
            echo "<div class='alert alert-danger'><b>$controller_name</b> Was  Not Found In Controller Directory. <b>Please Check </b>" . CONTROLLERS_DIR."</div>";
        }
        else{
            $this->page_not_found("<b>$controller_name</b> Was  Not Found In Controller Directory. <b>Please Check </b>" . CONTROLLERS_DIR);
        }
    }
}

路由器第92行:

/**
     * Start page Dispatch From Current URl
     * @var string
     */
    function init(){

        $basepath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';

        // for now, we are only interested with the path only.
        $page_url  = substr($_SERVER['REQUEST_URI'], strlen($basepath)); 
        $path = parse_url( $page_url, PHP_URL_PATH );

        if(!empty( $path )){
            $this->run( $path ); //LINE 92
        }
        else{
            self::$page_name = DEFAULT_PAGE;
            self::$page_action = DEFAULT_PAGE_ACTION;

            $controller_name = ucfirst(DEFAULT_PAGE)."Controller";
            $controller = new IndexController;
            $controller->{DEFAULT_PAGE_ACTION}(); 
        }
    }

完整的查看功能:

/**
    * View Record Action 
    * @return View
    */
    function view( $rec_id = null , $value = null){
    $db = $this->GetModel();
    $fields = array( 'post_id',     'post_title',   'post_text',    'post_date',    'post_user_posted' );
        if( !empty($value) ){
            $db->where($rec_id, urldecode($value));
        }
        else{
            $db->where('post_id' , $rec_id);
        }
    $record = $db->getOne( 'postagens', $fields );
        if(!empty($record)){

        $ActiveUser = USER_NAME;
        $meu_id         = $rec_id;
        $db->rawQuery("UPDATE postagens SET post_user_posted='$ActiveUser' WHERE post_id='$meu_id'"); //MY UPDATE QUERY
        render_json($records); //THE RENDER ONLY RETURN DATA IF I REMOVE THE UPDATE QUERY
        }
        else{
            if($db->getLastError()){
                render_error($db->getLastError());
            }
            else{
                render_error("Registro não encontrado",404);
            }
        }
        }    

有人知道为什么json无法正确渲染吗?

1 个答案:

答案 0 :(得分:1)

尝试一下(注意大括号):

$db->rawQuery("UPDATE `postagens` SET post_user_posted='{$ActiveUser}' WHERE post_id='{$meu_id}'");

或使用更具可读性的PDO prepared statements

通常,如果您想知道查询出了什么问题,可以将它们嵌入try / catch块中,并查看捕获的异常是什么。像这样:

try {
    $db->rawQuery("UPDATE postagens SET post_user_posted='{$ActiveUser}' WHERE post_id='{$meu_id}'");
    render_json($records);
} catch(\Exception $e) {
   // this is the error:
   // $e->getMessage();
}

不相干的是,您正在为变量混合使用不同的命名约定,这是一种不好的做法!