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 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误