[英]PDO clause where using for
示例我有這樣的數組:
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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.