Я создаю небольшой интернет-магазин, в котором я могу создавать новые продукты, в последнее время он вообще не работал, он должен работать так -> я вставляю название, цену, затем я выбираю одну из трех категорий ( Книги, жесткие диски и мебель), затем, на основании которого я выбираю новую вставку, например, для книг появляется вставка веса для мебели. Появляются три вставки: Ширина, Длина и Высота, которые использовались, только если я вставил все значения для одной категория (как я также должен был бы вставить ширину длины и высоты и другой, который является размером, а затем он будет вставлен в базу данных, теперь он просто не работает вообще, и я не знаю, где моя ошибка )
Вот create_product.php
с формой (я использую display none, а затем jquery, чтобы показать, какие категории вставки появляются (возможно, это не правильный способ go об этом?) )
<?php
// include database and object files
include_once 'config/database.php';
include_once 'objects/product.php';
include_once 'objects/category.php';
// get database connection
$database = new Database();
$db = $database->getConnection();
// pass connection to objects
$product = new Product($db);
$category = new Category($db);
// set page headers
$page_title = "Create Product";
include_once "layout_header.php";
echo "<div class='right-button-margin'>";
echo "<a href='index.php' class='btn btn-default pull-right'>Read Products</a>";
echo "</div>";
?>
<?php
// if the form was submitted
if($_POST){
// set product property values
$product->name = $_POST['name'];
$product->price = $_POST['price'];
$product->category_id = $_POST['category_id'];
$product->size = $_POST['size'];
$product->weight = $_POST['weight'];
$product->lenght = $_POST['lenght'];
$product->width = $_POST['width'];
$product->height = $_POST['height'];
// create the product
if($product->create()){
echo "<div class='alert alert-success'>Product was created.</div>";
}
// if unable to create the product, tell the user
else{
echo "<div class='alert alert-danger'>Unable to create product.</div>";
}
}
?>
<!-- HTML form for creating a product -->
<script>
// script for when you change the categories so that the appropriate input field appears
$(document).ready(function(){
$('.form-control').on('change', function() {
if ( this.value == 1)
{
$("#weight").show();
$("#size").hide();
$("#height").hide();
}
if ( this.value == 2)
{
$("#weight").hide();
$("#size").show();
$("#height").hide();
}
if ( this.value == 3)
{
$("#weight").hide();
$("#size").hide();
$("#height").show();
}
});
});
</script>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<table class='table table-hover table-responsive table-bordered'>
<tr>
<td>Name</td>
<td><input type='text' name='name' class='form-control' /></td>
</tr>
<tr>
<td>Price</td>
<td><input type='text' name='price' class='form-control' /></td>
</tr>
<div >
<tr id="weight" style="display:none">
<td >Weight</td>
<td><input type="text" name='weight' class='form-control'></input></td>
</tr>
</div>
<tr id="size" style="display:none">
<td>Size</td>
<td><input name='size' class='form-control'></input></td>
</tr>
<tr id="height" style="display:none">
<td>Height</td>
<td><input name='height' class='form-control'></input></td>
<td>Length</td>
<td><input name='lenght' class='form-control'></input></td>
<td>Width</td>
<td><input name='width' class='form-control'></input></td>
</tr>
<tr>
<td>Category</td>
<td>
<?php
// read the product categories from the database
$stmt = $category->read();
// put them in a select drop-down
echo "<select class='form-control' name='category_id'>";
echo "<option>Select category...</option>";
while ($row_category = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row_category);
echo "<option value='{$id}'>{$name}</option>";
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td></td>
<td>
<button type="submit" class="btn btn-primary">Create</button>
</td>
</tr>
</table>
</form>
<?php
// footer
include_once "layout_footer.php";
?>
и вот product.php
, где происходит запрос
<?php
class Product{
// database connection and table name
private $conn;
private $table_name = "products";
// object properties
public $id;
public $name;
public $price;
public $category_id;
public $size;
public $weight;
public $lenght;
public $width;
public $height;
public function __construct($db){
$this->conn = $db;
}
function create(){
//write query
$this->size = !empty($this->size) ? $this->size: null;
$this->weight= !empty($this->weight) ? $this->weight : null;
$this->lenght= !empty($this->lenght) ? $this->lenght : null;
$this->width= !empty($this->width) ? $this->width : null;
$this->height= !empty($this->height) ? $this->height : null;
$query = "INSERT INTO
" . $this->table_name . "
VALUES
name=:name, price=:price, category_id=:category_id, size=:size, weight=:weight, lenght=:lenght, width=:width,height=:height";
$stmt = $this->conn->prepare($query);
// bind values
$stmt->bindParam(":name", $this->name);
$stmt->bindParam(":price", $this->price);
$stmt->bindParam(":category_id", $this->category_id);
$stmt->bindParam(":size", $this->size);
$stmt->bindParam(":weight", $this->weight);
$stmt->bindParam(":lenght", $this->lenght);
$stmt->bindParam(":width", $this->width);
$stmt->bindParam(":height", $this->height);
if(!empty($stmt->execute())){
return true;
}else{
return false;
}
}
}
?>
В моей базе данных все атрибуты (размер, вес, e т c. ) установлены на то, что они могут быть NULL
, поэтому проблем не должно быть