PDO数组如果记录已经存在

时间:2018-01-30 11:38:38

标签: php mysql arrays pdo insert

我通过使用数组从一个提交按钮插入多行。记录的插入工作顺利。现在我想停止插入数据,如果已经存在记录。我的单记录更新语法可以防止多次插入相同的记录。但我很困惑,在使用数组时无法理解。我已经尝试了很多,但每个方法都显示错误。

此代码正常运作。

if(isset($_POST['submit'])){
    $number = $_POST['number'];
    $letter = $_POST['letter'];

    $sql = "INSERT INTO class(number, letter) VALUES(:number, :letter)";
    $query = $con->prepare($sql);

    foreach($number AS $key => $n){
        $query->bindParam(':number', $number[$key]);
        $query->bindParam(':letter', $letter[$key]);
        $query->execute();
    }
}

我的意图是,如果已插入数据,则停止插入数据。所以我试过这样的。我确定这是错误的,因为数组变量不能传递给第一语法**(sql1)**而 $ query 没有被访问到foreach子句。我不知道,所以我就这样使用了。请告诉我任何想法停止已经插入的记录。

我想更改此代码

<?php
if(isset($_POST['submit'])){
    $number = $_POST['number'];
    $letter = $_POST['letter'];

    $sql1 = 'SELECT COUNT(*) FROM class WHERE number = :number';
    $stmt = $con->prepare($sql1);
    $stmt->bindParam(':number', $number[$key]);
    $stmt->execute();

    if($stmt->fetchColumn()){
        echo"<script>alert('Class is already existed')</script>";
    }
    else{
        $sql = "INSERT INTO class(number, letter) VALUES(:number, :letter)";
        $query = $con->prepare($sql);
    }
    foreach($number AS $key => $n){
        $query->bindParam(':number', $number[$key]);
        $query->bindParam(':letter', $letter[$key]);
        $query->execute();
    }
}

?>

此代码显示以下错误

Notice: Undefined variable: key in C:\xampp\htdocs\marksheet\class.php on line 53
Notice: Undefined variable: query in C:\xampp\htdocs\marksheet\class.php on line 57
Fatal error: Uncaught Error: Call to a member function bindParam() on null in C:\xampp\htdocs\marksheet\class.php:57 Stack trace: #0 {main} thrown in C:\xampp\htdocs\marksheet\class.php on line 57

2 个答案:

答案 0 :(得分:2)

这应该有效:

if (isset($_POST['submit'])) {
    if(!empty($_POST['number']) && !empty($_POST['letter']) )
    {
        $number = $_POST['number'];
        $letter = $_POST['letter'];
        // Assuming both $number and $letter 1 dimensional array with equal number of indexes
        $notInsertedKey = [];
        foreach ($number AS $key => $item) {               

            /* Checking Existence*/
            $sql1 = 'SELECT COUNT(*) as counted FROM class WHERE number = :number';
            $stmt = $con->prepare($sql1);
            $stmt->bindParam(':number', $number[$key]);
            $stmt->execute();
            $data = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($data['counted'] < 1) {
                // echo "Not Exist";

                $sql = "INSERT INTO class(number, letter) VALUES (:number, :letter)";
                $query = $con->prepare($sql);
                $query->bindParam(':number', $number[$key]);
                $query->bindParam(':letter', $letter[$key]);
                $query->execute();

            } else {
                $notInsertedKey[] = $key;
                // Incase you want to know the failed indexes.
                echo "<script>alert('Class is already existed')</script>";
            }
        }
    }
}

更新

@AlivetoDie 建议的解决方案很适合作为插入唯一数据并删除重复数据的简写方法。但是,它没有任何方法可以跟踪失败的数据索引,因为查询始终返回TRUE。

答案 1 :(得分:1)

我想推荐以下方式。首先,您需要一个动态函数,它应该检查相关表中的记录

function isExist($columnName, $columnValue, $tableName){
        $columnName     = (!empty($columnName)) ? $columnName : 'empty';
        $columnValue    = (!empty($columnValue)) ? $columnValue : 'empty';
        $tableName  = (!empty($tableName)) ? $tableName : 'empty';
        $exist = 0;
        if($columnName != 'empty' && $columnValue != 'empty' && $tableName != 'empty'){
            $sql = "select * from `".$tableName."` where `".$columnName."` = '".$columnValue."'";
            $isExist = mysqli_query($this->connection,$sql);
            if(mysqli_num_rows($isExist) > 0){
                $exist = 1;

            }
        }
      return $exist;    
    }

然后按照以下方式在您的函数中使用它

if(isset($_POST['submit'])){
    $error = 0; 
    $response = array();
    $number = $_POST['number'];
    $letter = $_POST['letter'];

    $number_name_exist = $this->isExist('number', $number, 'class');
    if($number_name_exist == 1){
       $error = 1;
        $response['error'] =  $number . ' is already exists';
    }

    if($error == 0){

        $sql = "INSERT INTO class(number, letter) VALUES(:number, :letter)";
        $query = $con->prepare($sql);

        foreach($number AS $key => $n){
            $query->bindParam(':number', $number[$key]);
            $query->bindParam(':letter', $letter[$key]);
            $query->execute();
        }

    }
}

在上面的示例中,您可以看到$error变量和$response数组,这将使您的脚本更具动态性,您可以防止重复插入,还可以检查多个列。