I have a code which insert some values into a database table. It is working properly. I wont to get errors like database connecting errors,duplicate entry. Here is my code. Untitled Document
<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;
?>
try this way
......
if($x == 1){
header("Location:../bloodreport.php");
}else{
$str = "error :" . $db->err();
?>
<script>
var erro= <?php echo '"error : ' . $db->err() . '"'; ?>;
</script>
......
You can wrap each critical statement in try...catch block and logging error.
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();
}
EDIT Later do :
<?php if (isset($errString) && $errString !== '') { ?>
<script>
var error = "<?php echo 'error : ' . $errString; ?>";
alert(error);
</script>
<?php } ?>
Also validate post before insertion http://php.net/manual/en/function.filter-input.php
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.