用于的PDO子句

时间:2013-08-06 04:43:24

标签: php mysql codeigniter pdo

示例我有这样的数组:

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已经存在?

1 个答案:

答案 0 :(得分:0)

像这样更改你的功能:

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";
}