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); } });

Database System Concepts
7th Edition
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Chapter1: Introduction
Section: Chapter Questions
Problem 1PE
icon
Related questions
Question

Can you explain why this code does not insert information into the database but displays an error with the text:
->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>

<style>
margin-top:20px;
form(
}
hbel(
width:100px;
text-align: left;
}
input, select(
margin-left: 10px;
}
notification {
color: red;
}
</style>
<form id="product_form" method="post">
<label for="eu">SKU</label>
<input type="text"-"you" mme-"you"><p>
<label for="rame">Name</label>
<input type="text" id-"name" name="rame><p>
<label for="price">Price (S)</label>
<input type="number" id="price"name="price"><p><
<label for "Tage">Typegoer:</hbel>
<select id-name->
<option value Type
<option value="styd Disk /option>
<option value-book">Book</option>
<option value="furniture > Furniture</option>
<elect><bpbp
<div id="additional-fields"></div>
<form>
ld (pedes (Type) addhyliseng('change', function(){
var gestelisks dypesuruld additional-fields);
5801333M
switch(this)
case s
}
});
Type ser</option>
<label for="size">Size (MB):</label><input type="number" id="size" name="size"
<p strong Please, provide size:</strong></p>"
break
case 'book':
borald
case 'furniture":
HTML-'<label for="weight">Weight (Kg):</hbel><input type="humber" id="weight" name
<p><strong Please, provide weight in Kg.</strong></p>
TM-'<label for="height">Height:</label><input type="number" id="height" name="hei
<label for width Wichh:</hbel><input type="humber" id="BUGPSegglingtes>width" name="<FUGPSCO
<label for="<FUGPSCordingss>length">Length:</label><input type=BIGPCerdiet number
name="EUGPSC
length"><p><dp+
<strong> Please, provide dimensions</strong></p>
break
}:
deseadyListener("click", function(event) {
susesses Defaul
Bydd("product_form).submit();
Transcribed Image Text:<style> margin-top:20px; form( } hbel( width:100px; text-align: left; } input, select( margin-left: 10px; } notification { color: red; } </style> <form id="product_form" method="post"> <label for="eu">SKU</label> <input type="text"-"you" mme-"you"><p> <label for="rame">Name</label> <input type="text" id-"name" name="rame><p> <label for="price">Price (S)</label> <input type="number" id="price"name="price"><p>< <label for "Tage">Typegoer:</hbel> <select id-name-> <option value Type <option value="styd Disk /option> <option value-book">Book</option> <option value="furniture > Furniture</option> <elect><bpbp <div id="additional-fields"></div> <form> ld (pedes (Type) addhyliseng('change', function(){ var gestelisks dypesuruld additional-fields); 5801333M switch(this) case s } }); Type ser</option> <label for="size">Size (MB):</label><input type="number" id="size" name="size" <p strong Please, provide size:</strong></p>" break case 'book': borald case 'furniture": HTML-'<label for="weight">Weight (Kg):</hbel><input type="humber" id="weight" name <p><strong Please, provide weight in Kg.</strong></p> TM-'<label for="height">Height:</label><input type="number" id="height" name="hei <label for width Wichh:</hbel><input type="humber" id="BUGPSegglingtes>width" name="<FUGPSCO <label for="<FUGPSCordingss>length">Length:</label><input type=BIGPCerdiet number name="EUGPSC length"><p><dp+ <strong> Please, provide dimensions</strong></p> break }: deseadyListener("click", function(event) { susesses Defaul Bydd("product_form).submit();
Expert Solution
steps

Step by step

Solved in 3 steps

Blurred answer
Knowledge Booster
File Input and Output Operations
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
  • SEE MORE QUESTIONS
Recommended textbooks for you
Database System Concepts
Database System Concepts
Computer Science
ISBN:
9780078022159
Author:
Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:
McGraw-Hill Education
Starting Out with Python (4th Edition)
Starting Out with Python (4th Edition)
Computer Science
ISBN:
9780134444321
Author:
Tony Gaddis
Publisher:
PEARSON
Digital Fundamentals (11th Edition)
Digital Fundamentals (11th Edition)
Computer Science
ISBN:
9780132737968
Author:
Thomas L. Floyd
Publisher:
PEARSON
C How to Program (8th Edition)
C How to Program (8th Edition)
Computer Science
ISBN:
9780133976892
Author:
Paul J. Deitel, Harvey Deitel
Publisher:
PEARSON
Database Systems: Design, Implementation, & Manag…
Database Systems: Design, Implementation, & Manag…
Computer Science
ISBN:
9781337627900
Author:
Carlos Coronel, Steven Morris
Publisher:
Cengage Learning
Programmable Logic Controllers
Programmable Logic Controllers
Computer Science
ISBN:
9780073373843
Author:
Frank D. Petruzella
Publisher:
McGraw-Hill Education