简体   繁体   English

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

[英]PDO: Json not rendering response when execute a database update

I want to register the currently logged in username in a database field when he view a page. 当他查看页面时,我想在数据库字段中注册当前登录的用户名。 The database is a MySQL, and the language is PHP (XAMPP local server) 数据库是MySQL,语言是PHP(XAMPP本地服务器)

This is the code I'm using: 这是我正在使用的代码:

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

When I open the page via web browser the database is updated sucessfull. 当我通过Web浏览器打开页面时,数据库已成功更新。 But although the database is updated correctly, the page returns the following error message: 但是,尽管数据库已正确更新,但是该页面返回以下错误消息:

!Error Processing Request. 错误处理请求。

At this point, the page should get the database information and display. 此时,页面应获取并显示数据库信息。 But whenever the above error appears, the page does not load the information from the database. 但是,每当出现以上错误时,该页面就不会从数据库中加载信息。 The page only displays the error message and the fields are blank. 该页面仅显示错误消息,并且这些字段为空白。

I think something must be happening with json rendering. 我认为json渲染一定发生了什么。 If I remove the UPDATE query code the error is not displayed and the database informations is correctly displayed. 如果删除UPDATE查询代码,则不会显示错误,并且数据库信息也会正确显示。 Also removing the code the json returns: 还要删除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"}

When I run the update query the json does not give a return (or return empty) 当我运行更新查询时,json不给出返回(或返回空)

The error log show this: 错误日志显示如下:

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 lines around 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 lines around 1611: 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 line 93: 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 line 227: 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);
        }
    }
}

Router line 92: 路由器线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}(); 
        }
    }

The complete view function: 完整的查看功能:

/**
    * 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);
            }
        }
        }    

Does anyone know why json is not properly rendering? 有谁知道为什么json无法正确渲染?

Try with this (note the curly brackets): 试试这个(注意大括号):

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

Or use PDO prepared statements which are more readable. 或者使用更具可读性的PDO 准备语句

In general, if you want to know what's wrong with your queries, you can embed them in try/catch blocks, and see what's the caught exception. 通常,如果您想知道查询出了什么问题,可以将它们嵌入try / catch块中,并查看捕获的异常是什么。 So something like: 所以像这样:

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();
}

On an unrelated note, you are mixing different naming conventions for your variables which is a bad practice! 无关紧要的是,您正在为变量混合使用不同的命名约定,这是不好的做法!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM