【问题标题】:PDO clause where using for使用 for 的 PDO 子句
【发布时间】:2013-08-06 04:43:24
【问题描述】:

例如我有这样的数组:

Array
(
    [0] => 2010140419
    [1] => 2010140420
    [2] => 20101140421
)

我创建这样的代码:

public function check_siswa($noInduk) {
        $cnoInduk = count($noInduk);
        for($i = 0; $i < $cnoInduk; $i++) {
            $sql = "SELECT no_induk FROM siswa WHERE no_induk = :noInduk";
            $q = $this->db->conn_id->prepare($sql);
            $q->bindParam(':noInduk', $noInduk[$i], PDO::PARAM_INT);
            $q->execute();
        }

        $q->rowCount();
        $result = $q->fetchColumn();
        print_r($result);
        exit();
    }

从上面的代码,我得到的结果:

2010140420

我有这样的数据库:

SELECT no_induk from siswa;
  no_induk  
------------
 2010140419
 2010140420

我的问题,如何得到结果错误 no_induk 2010140419 和 2010140420 已经存在?

【问题讨论】:

  • 我不确定我是否理解您的问题。你想要什么输出,为什么?
  • Sory kba for My English.. 但是 maximus2012 已经回答了我的问题

标签: php mysql codeigniter pdo


【解决方案1】:

像这样改变你的函数:

public function check_siswa($noInduk) {
    $cnoInduk = count($noInduk);

    // error to hold the keys that are duplicate
    $error = Array();
    for($i = 0; $i < $cnoInduk; $i++) {
        $sql = "SELECT no_induk FROM siswa WHERE no_induk = :noInduk";
        $q = $this->db->conn_id->prepare($sql);
        $q->bindParam(':noInduk', $noInduk[$i], PDO::PARAM_INT);
        $q->execute();
        if ($q->rowCount() > 0){
            // if the key already exists then add it to the 
            // error array
            $error[] = $noInduk[$i];
        }
   }
   // there are some keys that exist already
   if (!empty($error)){
       return $error;
   }
   // no duplicates return false
   else {
       return false;
   }
}

那么对于函数调用:

if(($error = check_siswa($noInduk)) !== false){
    // there is an error
    echo "Keys exist already";
    var_dump ($error);
}
else {
    echo "No key exists already";
}

【讨论】:

  • 非常感谢 Maximus2012.. :D
猜你喜欢
  • 2014-12-13
  • 2014-12-13
  • 1970-01-01
  • 1970-01-01
  • 2017-04-08
相关资源
最近更新 更多