Can you explain why this code does not insert information into the database but displays an error with the text: ->Please select a product typePlease enter a product namePlease enter a valid product pricePlease enter a product SKUPlease enter a product attribute rest of the code as image setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'Error connecting to database: ' . $e->getMessage(); exit; } // Report all PHP errors error_reporting(E_ALL); // Display errors ini_set('display_errors', 1); ini_set('display_startup_errors', 1); if ($_SERVER['REQUEST_METHOD'] === 'POST') { // retrieve form data $type = $_POST['type'] ?? ''; $name = $_POST['name'] ?? ''; $price = $_POST['price'] ?? ''; $sku = $_POST['sku'] ?? ''; $attribute = $_POST['attribute'] ?? ''; //Perform validation $errors = []; if (!$type) { $errors[] = 'Please select a product type'; } if (!$name) { $errors[] = 'Please enter a product name'; } if (!$price || !is_numeric($price)) { $errors[] = 'Please enter a valid product price'; } if (!$sku) { $errors[] = 'Please enter a product SKU'; } else { $sql = "SELECT * FROM products WHERE sku = ?"; $stmt = $pdo->prepare($sql); $stmt->execute([$sku]); $result = $stmt->fetch(); if ($result) { $errors[] = 'A product with that SKU already exists'; } } if (!$attribute) { switch ($type) { case 'furniture': $errors[] = 'Please enter the dimensions of the furniture; break; case 'disk': $errors[] = 'Please enter the capacity of the disk'; break; default: $errors[] = 'Please enter a product attribute'; break; } } // if there are errors, return to the form page with error messages if (count($errors) > 0) { $errorString = implode('', $errors); echo ''; exit; } //Insert the new product into the database using PDO-prepared statements try { $sql = "INSERT INTO products (type, name, price, sku, `attribute`) VALUES (?, ?, ?, ?, ?)"; $stmt = $pdo->prepare($sql); $stmt->execute([$type, $name, $price, $sku, $attribute]); if ($stmt->rowCount() > 0) { // redirect to the product list page with a success message echo ''; exit; } // if the insert failed, return to the form page with an error message echo ''; exit; } catch (PDOException $e) { // if there was an error inserting the product, return to the form page // if there was an error inserting the product, return to the form page with an error message echo ''; exit; } } ?> Add Product Product Add Save Cancel function saveAndRedirect() { // Get the form data and submit it to the server via an AJAX request var form = document.getElementById('product_form'); var formData = new FormData(form); $.ajax({ url: 'save-product.php', type: 'POST', data: formData, processData: false, contentType: false, success: function() { // Redirect to the product list page after the save operation is complete window.location.href = 'index.php'; }, error: function(jqXHR, textStatus, errorThrown) { console.error('Error saving product: ' + textStatus, errorThrown); } });
Can you explain why this code does not insert information into the
->Please select a product type<br>Please enter a product name<br>Please enter a valid product price<br>Please enter a product SKU<br>Please enter a product attribute
rest of the code as image
<?php
require_once '../src/db/Db.php';
//attempt to connect to the database
try {
$pdo = Db::getConnection();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Error connecting to database: ' . $e->getMessage();
exit;
}
// Report all PHP errors
error_reporting(E_ALL);
// Display errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// retrieve form data
$type = $_POST['type'] ?? '';
$name = $_POST['name'] ?? '';
$price = $_POST['price'] ?? '';
$sku = $_POST['sku'] ?? '';
$attribute = $_POST['attribute'] ?? '';
//Perform validation
$errors = [];
if (!$type) {
$errors[] = 'Please select a product type';
}
if (!$name) {
$errors[] = 'Please enter a product name';
}
if (!$price || !is_numeric($price)) {
$errors[] = 'Please enter a valid product price';
}
if (!$sku) {
$errors[] = 'Please enter a product SKU';
} else {
$sql = "SELECT * FROM products WHERE sku = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$sku]);
$result = $stmt->fetch();
if ($result) {
$errors[] = 'A product with that SKU already exists';
}
}
if (!$attribute) {
switch ($type) {
case 'furniture':
$errors[] = 'Please enter the dimensions of the furniture;
break;
case 'disk':
$errors[] = 'Please enter the capacity of the disk';
break;
default:
$errors[] = 'Please enter a product attribute';
break;
}
}
// if there are errors, return to the form page with error messages
if (count($errors) > 0) {
$errorString = implode('<br>', $errors);
echo '<script>';
echo "alert('$errorString');";
echo "window.location.href = 'add-product.php';";
echo '</script>';
exit;
}
//Insert the new product into the database using PDO-prepared statements
try {
$sql = "INSERT INTO products (type, name, price, sku, `attribute`) VALUES (?, ?, ?, ?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$type, $name, $price, $sku, $attribute]);
if ($stmt->rowCount() > 0) {
// redirect to the product list page with a success message
echo '<script>';
echo "alert('Product added successfully');";
echo "window.location.href = 'index.php';";
echo '</script>';
exit;
}
// if the insert failed, return to the form page with an error message
echo '<script>';
echo "alert('There was an error adding the product');";
echo "window. location.href = 'add-product.php';";
echo '</script>';
exit;
} catch (PDOException $e) {
// if there was an error inserting the product, return to the form page
// if there was an error inserting the product, return to the form page with an error message
echo '<script>';
echo "alert('There was an error adding the product: {$e->getMessage()}');";
echo "window.location.href = 'add-product.php';";
echo '</script>';
exit;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Add Product</title>
<!-- Include CSS and JS files -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"
integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ=="
crossorigin="anonymous" referrerpolicy="no-referrer"/>
<link rel="stylesheet" href="style.css">
<!-- Add a script tag to include jQuery library -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container">
<div class="row mt-1 mb-1">
<div class="col-md-12">
<div style="display: flex; justify-content: space-between; border-bottom: 1px solid #ccc; padding: 20px 0;">
<div style="font-size: 24px;">Product Add</div>
<div>
<button id="save-btn" class="btn btn-secondary" onclick="saveAndRedirect()" style="font-size: 15px; padding: 10px 20px; margin-right: 15px;">Save</button> <!-- Removed "href" attribute -->
<button id="cancel-btn" class="btn btn-secondary" onclick="location.href='index.php'" style="font-size: 15px; padding: 10px 20px;">Cancel</button>
</div>
<script>
function cancel() {
if (confirm('Are you sure you want to cancel adding the product?')) {
window.location.href = 'index.php';
}
}
</script
<script>
function saveAndRedirect() {
// Get the form data and submit it to the server via an AJAX request
var form = document.getElementById('product_form');
var formData = new FormData(form);
$.ajax({
url: 'save-product.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function() {
// Redirect to the product list page after the save operation is complete
window.location.href = 'index.php';
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('Error saving product: ' + textStatus, errorThrown);
}
});
</script>
</div>
Step by step
Solved in 3 steps