如何在javascript警告框中显示sql错误消息?

时间:2015-11-08 12:25:53

标签: javascript mysql

我有一个代码可以将一些值插入到数据库表中。它运作正常。我不会得到像数据库连接错误,重复输入的错误。这是我的代码。                         无标题文档     

<body>
<?php
require '../classes/dbconnect.php';

$PId=$_POST["PatientId"];
$pName=$_POST["NameOfPatient"];
$age=$_POST["AgeOfPatient"];
$lId=$_SESSION['username'];
$fbs=$_POST["FBS"];
$sc=$_POST["Serum"];
$bu=$_POST["urea"];
$sgot=$_POST["sgot"];
$sgpt=$_POST["sgpt"];
$sa=$_POST["SAP"];
$sp=$_POST["protein"];
$sea=$_POST["albumin"];
$globulin=$_POST["globulin"];
$date=$_POST["date"];
$_SESSION['FBS'] = $fbs;


$db = new Database("localhost", "root", "", "mlab");
$x = $db->insert("INSERT INTO blood_report VALUES
('$PId','$lId','$date','$pName','$age','$fbs','$sc','$bu','$sgot','$sgpt','$s    a','$sp','$sea','$globulin')");

if($x == 1){
    header("Location:../bloodreport.php");
}else{
    $str = "error :" . $db->err();
    ?>
    <script>
    var erro= '<?php echo "error :" . $db->err(); ?>';
    </script>
    <?php
    //echo $str;
    echo '<script type="text/javascript">alert("Duplicate entry");history.go(-1);</script>';
}
echo $x;

?>

2 个答案:

答案 0 :(得分:1)

试试这种方式

......
if($x == 1){
   header("Location:../bloodreport.php");
}else{
   $str = "error :" . $db->err();
   ?>
<script>
    var erro= <?php echo '"error : '  . $db->err() . '"';  ?>;
</script>
......

答案 1 :(得分:0)

您可以将每个关键语句包装在try ... catch块和日志记录错误中。

try {
$db = new Database("localhost", "root", "", "mlab");
} catch (Exception $e) {
$errString = $e->getMessage(); 
}

try {
    $x = $db->insert("INSERT INTO blood_report VALUES
('$PId','$lId','$date','$pName','$age','$fbs','$sc','$bu','$sgot','$sgpt','$s    a','$sp','$sea','$globulin')");
} catch (Exception $e) {
$errString = $e->getMessage(); 
}

修改 后来做:

<?php if (isset($errString) && $errString !== '') { ?>
<script>
var error = "<?php echo 'error : ' . $errString; ?>";
alert(error);
</script>
<?php } ?>

在插入http://php.net/manual/en/function.filter-input.php

之前验证帖子