【问题标题】:fetch records from 2 tables and check if submitted checkbox id value exist从 2 个表中获取记录并检查提交的复选框 id 值是否存在
【发布时间】:2017-08-14 06:10:16
【问题描述】:

我有这个从

获取复选框结果的表单
  1. 标签

现在我想比较提交的帖子 ID 和值是否存在于表中并抛出错误

$stmt = $db->prepare('SELECT * FROM posts_tags WHERE post_id = :post_id AND tag_id = :tag_id');
        $stmt->bindParam(':post_id', $postID, PDO::PARAM_INT);
        $stmt->bindParam(':tag_id', $postTag, PDO::PARAM_INT);
        $r = $stmt->rowCount();

        if(!empty($r)){
            $error[] = 'Please do not select exsisting tag.';
}

这是我表单中的一些代码

<input type='hidden' name='postID' value='<?php echo $row['postID'];?>'>
<p><label>Tags</label><br />
        <div class="boxcheck">
        <?php                   
                    $stmt = $db->prepare('select * from blog_tags');
                    $stmt->execute();
                    $tag = $stmt->fetchAll();
                    foreach($tag as $tags){
                    ?>
                    <input type="checkbox" name="postTag[]" value="<?php echo $tags['tagID']; ?>"> <?php echo $tags['tagName']; ?><br /> 

                    <?php
                    }
                    ?>

如果错误没有发生,我可能会做什么?

感谢你们的帮助

【问题讨论】:

    标签: php pdo


    【解决方案1】:

    1st : $postTag 是数组,您将其绑定为 int 。

    第二个:你需要在查询中使用IN子句

    第三:你需要这样绑定值。

    $inClause=array();
    $i=1;
    foreach($postTag as $row){
      $inClause[]=':postTag'.$i;
      $i++;
    }
    
    $stmt = $db->prepare('SELECT * FROM posts_tags WHERE post_id = :post_id AND tag_id IN ('.explode(',',$inClause).')');
            $stmt->bindParam(':post_id', $postID, PDO::PARAM_INT);
    
    $i=1;
    foreach($postTag as $row){
      $stmt->bindParam('postTag'.$i, $row, PDO::PARAM_INT);
      $i++;
    }
    $res =    $stmt->execute();
    $r = $stmt->rowCount();
    

    【讨论】:

    • 如果 post_tags 表中存在 post_id 和 tag_)id 仍然没有错误出现 $r = $stmt->fetch(PDO::FETCH_ASSOC); if(!empty($r)){ $error[] = '标签存在。'; }
    • 你忘了执行查询$stmt-&gt;execute();@ChristineMay
    • 得到这个致命错误:未捕获的异常 'PDOException' 带有消息 'SQLSTATE[HY093]:无效的参数号:绑定变量的数量与令牌的数量不匹配'
    • 很高兴它帮助你:) @ChristineMay
    • 你是个善良而乐于助人的人:-*
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 2018-01-31
    • 2021-08-08
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多