如何在PHP中处理完整性约束外键

时间:2018-12-23 07:37:33

标签: php constraints integrity

我正在尝试测试代码,我知道当我输入原始表中不可用的外键值时,我会得到外键完整性约束。我的问题是如何在PHP PDO中处理此问题,以便在不使用try catch的情况下将错误消息提供给客户端?我正在从设备表呼叫(eqt_id),为患者表呼叫(Patient_id)。

这是错误:

致命错误:未捕获的PDOException:SQLSTATE [23000]:违反完整性约束:1452无法添加或更新子行:外键约束失败(smartmedeqtvisit,CONSTRAINT {{1} } C:\ xampp \ htdocs \ smartmed \ eqtaddvst.php:63中的引用eqtvisit_ibfk_2eqt_id)在删除级联上的equipmenteqt_id):堆栈跟踪:#0 C:\ xampp \ htdocs \ smartmed \ eqtaddvst.php(63):PDOStatement-> execute()#1 {main}放在第63行的C:\ xampp \ htdocs \ smartmed \ eqtaddvst.php中

这是我的代码:

$error = false;
   if(isset($_POST['eqtAddVst'])){

 //Retrieve the field values from our registration form.
$eqtid = !empty($_POST['eqt_id']) ? trim($_POST['eqt_id']) : 
    $error=true;
$patientid = !empty($_POST['patient_id']) ? trim($_POST['patient_id']) 
: $error=true;
 $eqtvisittype = !empty($_POST['eqtvisit_type']) ? 
 trim($_POST['eqtvisit_type']) : $error=true;
 $eqtvisitindate = !empty($_POST['eqtvisit_indate']) ? 
 trim($_POST['eqtvisit_indate']) : $error=true;
$eqtvisitintime = !empty($_POST['eqtvisit_intime']) ? 
 trim($_POST['eqtvisit_intime']) : $error=true;
$eqtvisitoutdate = !empty($_POST['eqtvisit_outdate']) ? 
 trim($_POST['eqtvisit_outdate']) : $error=true;
$eqtvisitouttime = !empty($_POST['eqtvisit_outtime']) ? 
 trim($_POST['eqtvisit_outtime']) : $error=true;



//the prepared statement is built and executed.
 if($error){

     echo '<script language="javascript">';
     echo 'alert("Must Enter All Records")';
     echo '</script>';
}

//Prepare our INSERT statement.

$sql = "INSERT INTO eqtvisit (eqtvisit_type, patient_id, eqt_id, eqtvisit_indate, eqtvisit_intime, eqtvisit_outdate, eqtvisit_outtime) 
VALUES (:eqtvisit_type, :patient_id, :eqt_id, :eqtvisit_indate, :eqtvisit_intime, :eqtvisit_outdate, :eqtvisit_outtime)";
$stmt = $conn->prepare($sql);

//Bind our variables.
$stmt->bindValue(':eqt_id', $eqtid);
$stmt->bindValue(':patient_id', $patientid);
$stmt->bindValue(':eqtvisit_type', $eqtvisittype);
$stmt->bindValue(':eqtvisit_indate', $eqtvisitindate);
$stmt->bindValue(':eqtvisit_intime', $eqtvisitintime);
$stmt->bindValue(':eqtvisit_outdate', $eqtvisitoutdate);
$stmt->bindValue(':eqtvisit_outtime', $eqtvisitouttime);

//Execute the statement and insert the new account.
$result = $stmt->execute();

//If the signup process is successful.
if($result){
    //What you do here is up to you!
     echo '<script language="javascript">';
     echo 'alert("Succeed")';
     echo '</script>';

0 个答案:

没有答案