I am doing a customer service Ticket submission to resolve the customer question, and when was doing the create new ticket from user, i done the data entry by it was not storing into the database the error keep saying that “Error: Unable to insert data into the database.” can anyone can help me to fix my code
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'db_connect.php';
class FormState
{
protected $pdo;
public function __construct($pdo)
{
$this->pdo = $pdo;
}
public function handleRequest($formData)
{
// Default behavior for handling form submission
return false;
}
protected function insertData($formData)
{
try {
$sql = "INSERT INTO ticket (userName, email, phoneNumber, address, city, state, postcode, issueType, issueSubject, issueDetails, productType, serialNumber, systemPassword, extraItem, ticketStatus)
VALUES (:userName, :email, :phoneNumber, :address, :city, :state, :postcode, :issueType, :issueSubject, :issueDetails, :productType, :serialNumber, :systemPassword, :extraItem, :ticketStatus)";
$stmt = $this->pdo->prepare($sql);
$stmt->bindParam(':userName', $formData['userName']);
$stmt->bindParam(':email', $formData['email']);
$stmt->bindParam(':phoneNumber', $formData['phoneNumber']);
$stmt->bindParam(':address', $formData['address']);
$stmt->bindParam(':city', $formData['city']);
$stmt->bindParam(':state', $formData['state']);
$stmt->bindParam(':postcode', $formData['postcode']);
$stmt->bindParam(':issueType', $formData['issueType']);
$stmt->bindParam(':issueSubject', $formData['issueSubject']);
$stmt->bindParam(':issueDetails', $formData['issueDetails']);
$stmt->bindParam(':productType', $formData['productType']);
$stmt->bindParam(':serialNumber', $formData['serialNumber']);
$stmt->bindParam(':systemPassword', $formData['systemPassword']);
$stmt->bindParam(':extraItem', $formData['extraItem']);
$stmt->bindValue(':ticketStatus', "pending/open");
if ($stmt->execute()) {
return true; // Success, return true
} else {
// Output the error message if execution fails
echo "Error executing SQL statement: " . $stmt->errorInfo();
return false; // Return false to indicate failure
}
} catch (PDOException $e) {
// Log or echo the error message for debugging purposes
echo "Error: " . $e->getMessage(); // Output the specific error message
return false; // Return false to indicate failure
}
}
}
// Check $_POST data
var_dump($_POST);
// new_ticket.php
$state = new FormState($pdo);
// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($state->handleRequest($_POST)) {
// Data inserted successfully, show alert
echo '<script>alert("Data saved successfully."); setTimeout(function(){ window.location.href = "tiketList.php"; }, 3000);</script>';
} else {
// Error occurred while inserting data
echo '<script>alert("Error: Unable to insert data into the database.");</script>';
}
}
?>
<style>
#regForm {
background-color: #ffffff;
margin: 100px auto;
font-family: Raleway;
padding: 40px;
width: 70%;
min-width: 300px;
}
h1 {
text-align: center;
}
input {
padding: 10px;
width: 100%;
font-size: 17px;
font-family: Raleway;
border: 1px solid #aaaaaa;
margin: 10px 0px 10px 0px;
}
select{
padding: 10px;
font-size: 17px;
border: 1px solid #aaaaaa;
margin: 10px 0px 10px 0px;
}
#backupData{
display: inline-block;
width: auto;
margin-left: 7%;
margin-bottom: 10px;
}
/* Mark input boxes that gets an error on validation: */
input.invalid {
background-color: #ffdddd;
}
/* Hide all steps by default: */
.tab {
display: none;
}
button {
background-color: #04AA6D;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
font-family: Raleway;
cursor: pointer;
margin: 10px 0px 0px 0px;
}
button:hover {
opacity: 0.8;
}
#prevBtn {
background-color: #bbbbbb;
}
/* Make circles that indicate the steps of the form: */
.step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
.step.active {
opacity: 1;
}
/* Mark the steps that are finished and valid: */
.step.finish {
background-color: #04AA6D;
}
</style>
<form id="regForm" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="tab">
<h2>Contact Information</h2>
<div>
<label for="userName">User Name *</label>
<input type="text" id="userName" name="userName" placeholder="User Name" required>
</div>
<div>
<label for="email">Email Address: *</label>
<input type="email" id="email" name="email" placeholder="Email Address" required>
</div>
<div>
<label for="phoneNumber">Phone Number *</label>
<input type="tel" id="phoneNumber" name="phoneNumber" placeholder="Phone Number" pattern="[0-9]{10,11}" required>
</div>
<div>
<label for="address">Address: </label>
<input type="text" id="address" name="address" pattern="[^ @]*@[^ @]*" placeholder="Address" optional>
</div>
<div>
<label for="city">City: </label>
<input type="text" id="city" name="city" placeholder="City" optional>
</div>
<div>
<label for="state">State/Province: </label>
<input type="text" id="state" name="state" placeholder="State/Province" optional>
</div>
<div>
<label for="postcode">Postcode</label>
<input type="text" id="postcode" name="postcode" placeholder="Postcode" pattern="d{5}" title="Please enter a correct postcode." optional>
</div>
</div>
<div class="tab">
<h2>Issue details</h2>
<div>
<label for="issueType">Issue Type *</label>
<br/>
<select id="issueType" name="issueType" required>
<option value=""></option>
<?php
// Use $pdo instead of $conn
$issueTypeQuery = $pdo->query("SELECT * FROM issue_type ORDER BY name ASC");
while($row = $issueTypeQuery->fetch(PDO::FETCH_ASSOC)):
?>
<option value="<?php echo $row['id'] ?>"><?php echo ucwords($row['name']) ?></option>
<?php endwhile; ?>
</select>
</div>
<div>
<label for="issueSubject">Issue Subject *</label>
<input type="issueSubject" id="issueSubject" name="issueSubject" placeholder="Need help with... " required>
</div>
<div>
<label for="issueDetails">Issue Details *</label>
<input type="issueDetails" id="issueDetails" name="issueDetails" placeholder="Detailed explanation of the issue">
</div>
<div>
<label for="productType">Product Type *</label>
<br/>
<select id="productType" name="productType" required>
<option value=" "> </option>
<option value="Desktop">Desktop</option>
<option value="Laptop">Laptop</option>
<option value="Monitor">Monitor</option>
<option value="Other">Other</option>
</select>
</div>
<div>
<label for="serialNumber">Product Serial Number *</label>
<input type="text" id="serialNumber" name="serialNumber" required>
</div>
<div>
<label for="systemPassword">Operating System Password</label>
<input type="text" id="systemPassword" name="systemPassword" optional>
</div>
<div>
<label for="extraItem">Other accessories sent in together (backpack, box etc)</label>
<input type="text" id="extraItem" name="extraItem" optional>
</div>
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
<div style="text-align:center;margin-top:40px;">
<span class="step"></span>
<span class="step"></span>
</div>
</form>
<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
//... and fix the Previous/Next buttons:
if (n === 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n === (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n);
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n === 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets submitted:
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value === "" && !y[i].hasAttribute("optional")) {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
// Additional validation for phone number
if (y[i].id === "phoneNumber" && !(/^d{10,11}$/.test(y[i].value))) {
y[i].className += " invalid";
valid = false;
}
// Validation for email
if (y[i].id === "email" && y[i].value !== "") {
var emailPattern = /^[^s@]+@[^s@]+.[^s@]+$/;
if (!emailPattern.test(y[i].value)) {
y[i].className += " invalid";
valid = false;
}
}
// Validation for postcode
if (y[i].id === "postcode" && y[i].value !== "") {
if (!(/^d{5}$/.test(y[i].value))) {
y[i].className += " invalid";
valid = false;
}
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class on the current step:
x[n].className += " active";
}
</script>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// db_connect.php
$host = 'localhost';
$dbname = 'customerservice_db';
$username = 'test';
$password = '1234';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
CREATE TABLE `tickets` (
`id` int(30) NOT NULL,
`userName` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`phoneNumber` int(20) NOT NULL,
`address` varchar(255) DEFAULT NULL,
`city` varchar(255) DEFAULT NULL,
`state` varchar(255) DEFAULT NULL,
`postcode` int(20) DEFAULT NULL,
`issueType` varchar(255) NOT NULL,
`issueSubject` varchar(255) NOT NULL,
`issueDetails` varchar(255) NOT NULL,
`productType` varchar(255) NOT NULL,
`serialNumber` varchar(255) NOT NULL,
`systemPassword` varchar(255) DEFAULT NULL,
`backupData` tinyint(1) NOT NULL,
`extraItem` varchar(255) NOT NULL,
`ticketStatus` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
the situation is like this, the user had completed input all the data but when the user click submit, it will have error saying that “Error: Unable to insert data into the database.”, i know i had assign this error handling, but i wtill dont know where the problem is, please someone help me