Pages

Saturday, 4 April 2020

Handle database run time error : PHP

Handle database run time Error : PHP

Error handling is important the same as coding because without error handling you can't get the actual problem when something is not happening as you want. Without error handling, you will waste your precious time and sometimes fail to achieve the task in a given deadline. So  I have made this post to handle PHP database run time error in a simple way.

Post Details

  • This post is designed to save contact page data
  • You will be redirected to the success page when data saved successfully otherwise error page with a related message.
  • Database code is in a class


Contact Page code


$msg="";
if(isset($_POST["submit"]))
{
$ob=new tradeinsert();

$msg=$ob->SaveContact($_POST["txtName"],$_POST["txtPhone"],$_POST["txtSubject"],$_POST["txtMessage"]);
if($msg=="1")
header("location:thanks.php?id=Thanks for contact us our representative will call you very soon");
else
header("location:error.php?id=$msg");
}

HTML Page 


<form  method="post">
    <div class="row">
        <div class="col-lg-6">
            <div class="form-group">
                <input type="text" class="form-control" name="txtName" placeholder="Your Name" value="" required>
            </div>
        </div>
        <div class="col-lg-6">
            <div class="form-group">
                <input type="text" class="form-control" name="txtPhone" placeholder="Your Phone" value="" pattern="[0-9]{10}" title="Only 10 digit phone number is allowed" required>
            </div>
        </div>
        <div class="col-12">
            <div class="form-group">
                <input type="text" class="form-control" name="txtSubject" placeholder="Your Subject">
            </div>
        </div>
        <div class="col-12">
            <div class="form-group">
                <textarea name="txtMessage" class="form-control"  cols="30" rows="10" placeholder="Your Message"></textarea>
            </div>
        </div>
        <div class="col-12">
                     <input type="submit" value="Send" class="btn credit-btn mt-30" name="submit">

        </div>
    </div>

</form>

Database Code

function SaveContact($name,$phone,$subject,$message)
{


$stmt = $this->conn->stmt_init();
if ($stmt->prepare("insert into  tradecontact  (id,name,phone,subject,message,createddate) values(NULL,?,?,?,?,?)"))
{
$stmt->bind_param("sssss", $a1, $a2, $a3,$a4,$a5) or   die( "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error);
$a1 = $name;
$a2 = $phone;
$a3 = $subject;
$a4 = $message;
$a5 =  date("Y-m-d");
if($stmt->execute()) 
echo "<h1>Error db</h1>". $stmt->error;
else
echo "<h1>else</h1>";      
$stmt->close();  
return "1";
}
else
{
return "dberror ".  mysqli_error($this->conn) ;

}      
}

No comments:

Post a Comment