duandi6531 2012-11-07 16:34
浏览 47
已采纳

PDO准备好的声明不适用于此查询

Im having this query:

$query = $db->query("SELECT

                      posts.post_topic_id,
                      posts.post_content,
                      posts.post_id,
                      posts.post_date,
                      posts.post_by,    
                      posts.post_votes_total,
                      posts.post_suggested_amount, 
                      posts.post_accepted,
                      posts.post_last_edited,
                      posts.post_edit_sum,
                      users.user_id,
                      users.username

                    FROM
                      posts

                    JOIN
                      users
                    ON
                      posts.post_by = users.user_id
                    WHERE
                      posts.post_topic_id = :topic_id
                    ORDER BY
                      :sort
                    LIMIT :start , :per_page
                  ");

$query->bindParam(':topic_id', $topic_id, PDO::PARAM_INT);
$query->bindParam(':sort', $sort, PDO::PARAM_STR);
$query->bindParam(':start', $start, PDO::PARAM_INT);
$query->bindParam(':per_page', $per_page, PDO::PARAM_INT);
$query->execute();

But it wont execute and give me and error instead:

exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':topic_id ORDER BY posts.post_id ASC ' at line 25' in C:\htdocs\lr\topic.php:577 Stack trace: #0 C:\htdocs\lr\topic.php(577): PDO->query('SELECT???? ...') #1 {main}

If I don't prepare the statements, and I use the normal variables, the query executes just fine.

What's my mistake?

  • 写回答

1条回答 默认 最新

  • dsrw29618 2012-11-07 16:38
    关注

    You mix up methods for prepared statements and simple queries. The bindParam() method just relates to prepared statements. On its own, the query() method tries to execute the given query immediately, which fails, because the parameters have not been substituted.

    To solve this, just change to prepared statements all along by using

    $query = $db->prepare("SELECT ... " );
    

    and then execute after binding all variables

    $query->exec();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?