PHP Prepared Statements处理重复条目

时间:2015-05-05 09:04:22

标签: php mysql mysqli error-handling prepared-statement

我遇到了问题,我无法处理带有预处理语句的重复条目。

我想在出现重复条目​​时结束程序。这就是我一直在努力做的事情:

function insert_vulnerability ($CVE, $Description, $Date, $Score, $Type){


    $conn = connection();

    $stmt = $conn->prepare("INSERT INTO Vulnerabilities (CVE, Description, Date, Score, Type)
                           VALUES (?, ?, ?, ?, ?)");




    $stmt->bind_param("sssis", $CVE, $Description, $Date, $Score, $Type);

    if ( false === $stmt ) {

       die('prepare() failed: ' . htmlspecialchars($mysqli->error));

    }


    $stmt->execute();

    $conn->close();


}

当不使用准备好的语句时,我以这种方式处理错误,一切都运行良好:

function insert_vulnerability ($CVE, $Description, $Date, $Score, $Type){


    $conn = connection();

    $Description = htmlspecialchars($Description);



    $sql = "INSERT INTO Vulnerabilities (CVE, Description, Date, Score, Type)
    VALUES ('".$CVE."', '".$Description."', '".$Date."', '".$Score."', '".$Type."')";

    if ($conn->query($sql) === TRUE) {
        //echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
        $conn->close();
        die();

    }

    $conn->close();

}

那么如何用准备好的陈述得到相同的结果?

提前谢谢。

1 个答案:

答案 0 :(得分:1)

您可以连接$stmt->execute()内的检查,看看准备好的语句是否正常工作。

function insert_vulnerability ($CVE, $Description, $Date, $Score, $Type){
    $conn = connection();

    $stmt = $conn->prepare('
        INSERT INTO Vulnerabilities (CVE, Description, Date, Score, Type)
        VALUES (?, ?, ?, ?, ?)
    ');

    $stmt->bind_param('sssis', $CVE, $Description, $Date, $Score, $Type);
    if($stmt->execute()) { // true, success, else error
        echo 'New record created successfully';
    } else {
        echo $conn->error;
    }

    $conn->close();
}

请注意,您准备好的声明方面有一个未定义的变量:

$mysqli->error