php - PDO 子句使用 for

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

最佳答案

像这样更改你的函数:

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 子句使用 for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18071936/

相关文章:

php - 如何从 Mysql 和 Codeigniter 中的两个表中获取数据

php - 在 Apache2/Cake PhP 中定义文档根目录

javascript - 未捕获的语法错误 : missing ) after argument list when write javascript in PHP code

php - Codeigniter 扩展 native 库

mysql - 如何将带有 Doctrine 2 的 INDEX 添加到列而不使其成为主键?

php - 如何根据条件在 php while 循环中填充两个不同的 html 表?

PHP 和 MySQL 总是为列插入 0

构造函数

php - CodeIgniter 更新查询不起作用

php - 插入查询成功但数据库出现错误?