示例我有这样的数组:

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

最佳答案

像这样更改您的功能:

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

关于php - PDO子句用于,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18071936/

10-09 15:19