dongyuzhu2244 2014-12-02 02:34
浏览 45
已采纳

PDO bindParam / Value的问题

I am trying to get a query from a database, however, the value I have for bindParam (:name) is not being bound, when I echo $sql and print_r($stmtTwo) the WHERE clause states WHERE :name instead of the string from $wherefinal.

The code I have is:

$sql= "SELECT Species.Species_ID 
    FROM Species 
    JOIN ( 
        SELECT Species.Species_ID, COUNT(*) AS mynum 
        FROM Species_Opt LEFT JOIN Species ON (Species.Species_ID = Species_Opt.SO_Species_ID) 
        WHERE :name
        GROUP BY SO_Species_ID HAVING mynum = 6 
        ) AS mytable ON Species.Species_ID = mytable.Species_ID";
$stmtTwo = $pdo->prepare($sql);
$stmtTwo->bindParam(':name', $wherefinal);
$stmtTwo->execute();

with $wherefinal being defined before the sql statement and being defined as:

$where = "";
foreach ($_POST as $k => $v){
    $where .= "(Species_Opt.SO_Option_ID = $v) OR "; 
};
$wherefinal = substr($where, 0, strrpos($where, " OR "));

And when echoed, $wherefinal displays:

(Species_Opt.SO_Option_ID = 4) OR (Species_Opt.SO_Option_ID = 12) OR (Species_Opt.SO_Option_ID = 17) OR (Species_Opt.SO_Option_ID = 20) OR (Species_Opt.SO_Option_ID = 21) OR (Species_Opt.SO_Option_ID = 32)

$v is from the value of a radio button from a form that is generated via a different SQL statement and smarty.

  • 写回答

1条回答 默认 最新

  • dp411805872 2014-12-02 04:37
    关注

    First thing first, you need to construct your placeholder part

    $placeholder = str_repeat('?,', count($_POST) - 1) . '?';
    

    Then use it to construct a full SQL query

    $sql= "SELECT Species.Species_ID 
           FROM Species 
           JOIN ( 
              SELECT Species.Species_ID, COUNT(*) AS mynum 
              FROM Species_Opt LEFT JOIN Species ON 
                   (Species.Species_ID = Species_Opt.SO_Species_ID) 
              WHERE Species_Opt.SO_Option_ID IN ({$placeholder})
           GROUP BY SO_Species_ID HAVING mynum = 6 
           ) AS mytable ON Species.Species_ID = mytable.Species_ID";
    

    After that, you can bind the value to each placeholder

    $sh = $pdo->prepare($sql);
    
    $i = 1;
    foreach($_POST as $value) {
        $sh->bindValue($i, $value); $i++;
    }
    $sh->execute();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度