pdo:json在执行数据库更新时不呈现响应

kuhbmx9i  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(303)

我想在他查看页面时在数据库字段中注册当前登录的用户名。数据库是mysql,语言是php(xampp local server)
这是我使用的代码:

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

当我通过web浏览器打开页面时,数据库更新成功。但是,尽管数据库已正确更新,页面仍返回以下错误消息:
!处理请求时出错。
此时,页面应该获得数据库信息并显示出来。但是每当出现上述错误时,页面都不会从数据库中加载信息。该页仅显示错误消息,字段为空。
我想json呈现一定发生了什么。如果删除更新查询代码,则不会显示错误,并且正确显示数据库信息。同时删除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"}

当我运行update查询时,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
        }
    }

关于1611的pdodb.php行:

/**
     * 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不能正确呈现吗?

vnjpjtjt

vnjpjtjt1#

试试这个(注意花括号):

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

或者使用pdo编写的更具可读性的语句。
通常,如果您想知道查询有什么问题,可以将它们嵌入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();
}

另一方面,您正在为变量混合不同的命名约定,这是一种糟糕的做法!

相关问题