使用PDO绑定值,插入IS NULL

时间:2015-09-12 12:28:30

标签: php pdo

我有这个功能:

  function fetch_article_comments($article_id, $parent_id) {

$app = new Connection();

    if ($parent_id > 0) {
        $parent_id = '= '. $parent_id;
    } else {
        $parent_id = "IS NULL";
    }
    $sql = "SELECT * FROM recursive WHERE article_id = :article_id AND comment_parent :parent_id ORDER BY comment_timestamp DESC";
    $query = $app->getConnection()->prepare($sql);

    try{
        $query->execute(array(':article_id' => $article_id,
                             ':parent_id' => $parent_id));
        $comments = $query->fetchAll();   //returns an stdClass
        $query->closeCursor();

        return $comments;

    } catch(PDOException $e){
        die($e->getMessage());
    }
}

我希望$parent_id成为IS NULL。但我收到此错误消息:

  

PHP警告:PDOStatement :: execute():SQLSTATE [42000]:语法错误   或访问冲突:1064您的SQL语法有错误;校验   与您的MySQL服务器版本对应的手册   语法使用附近'' IS NULL' ORDER BY comment_timestamp DESC'

为了干净整洁的代码,我不想在if语句中使用整个查询。

$parent_id如何设置为IS NULL而不是'IS NULL'

2 个答案:

答案 0 :(得分:3)

您正试图以不允许的方式使用条件语句和参数绑定。

尝试更改此内容......

NSLog(@"AppDelegate application 2");
NSLog(@"window: %@", window); 
NSLog(@"navigationController: %@", navigationController);
[window addSubview:[navigationController view]];
NSLog(@"AppDelegate application 3");


2015-09-12 14:24:35.251 SWPi[1209:607] AppDelegate application 2
2015-09-12 14:24:35.270 SWPi[1209:607] window: <UIWindow: 0x79fcdd80; frame = (0 0; 768 1024); autoresize = RM+BM; gestureRecognizers = <NSArray: 0x79fd3860>; layer = <UIWindowLayer: 0x79f721e0>>
2015-09-12 14:24:35.271 SWPi[1209:607] navigationController: <UINavigationController: 0x79fc8030>
2015-09-12 14:24:35.273 SWPi[1209:607] CRASH: *** -[__NSArrayM insertObject:atIndex:]: object cannot be nil

到此......

    if ($parent_id > 0) {
        $parent_id = '= '. $parent_id;
    } else {
        $parent_id = "IS NULL";
    }
$sql = "SELECT * FROM recursive WHERE article_id = :article_id AND comment_parent :parent_id ORDER BY comment_timestamp DESC";

快乐的编码!

答案 1 :(得分:1)

$app = new Connection();

function fetch_article_comments($article_id, $parent_id, $app) {

    if ($parent_id <= 0) {
        $parent_id = NULL;
    }
    $sql = "SELECT * FROM recursive WHERE article_id = :article_id AND comment_parent <=> :parent_id ORDER BY comment_timestamp DESC";
    $query = $app->getConnection()->prepare($sql);

    $query->execute(array(':article_id' => $article_id,
                             ':parent_id' => $parent_id));
    return $query->fetchAll();
}