Reputation: 15
I have done some database normalization and made for the product table a foreign producttype table because of the fixed value's. Now i run into some php form problems.
I am trying to make work: adding a product and make a producttype option (producttypes from pull-down list) and store only the producttypeid to the product record.
My tables:
product (productname, producttype)
producttype (producttypeid, producttype
There are two records into the producttype table database that should been showed in the pull-down. My updated code is as follow
<?php
// connection with database
include('connect.php');
// check page request
if (isset($_POST["submit"])){
// query insert to product
$sql="INSERT INTO product (productname, producttype)
VALUES('$_POST[productname]','$_POST[producttype]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
// query select from producttype
$query="SELECT producttypeid, producttype FROM producttype";
$result = mysql_query($query) or die ("Error: " . mysql_error());
// store options in array
$product_types = array();
while (list($id, $name,) = mysql_fetch_row($result))
{
$product_types[$id] = $name;
}
// safety against cross-site scripting
function h($str)
{
return htmlentities($str, ENT_QUOTES, "UTF-8");
}
}?>
<!-- html input form !-->
<html>
<body>
<form action="addproduct.php" method="post">
<input type="hidden" name="submit" value="1">
Productname: <input type="text" name="productname"></br>
Producttype: <select>
<?php foreach($product_types as $id => $label): ?>
<option value="<?php echo h($id); ?>"><?php echo h($label); ?></option>
<?php endforeach; ?>
</select></br>
<input type="submit">
</form>
</body>
</html>
Upvotes: 0
Views: 143
Reputation: 5977
You have only one <option>
tag within your <select>
. To display all product types in the select menu, you'll need to store the options in an array:
$product_types = array();
while (list($id, $name,) = mysql_fetch_row($result))
{
$product_types[$id] = $name;
}
Then to display the options:
<select>
<?php foreach($product_types as $id => $label): ?>
<option value="<?php echo h($id); ?>"><?php echo h($label); ?></option>
<?php endforeach; ?>
</select>
The h
function is used to escape the output so that your code won't be vulnerable to cross-site scripting:
function h($str)
{
return htmlentities($str, ENT_QUOTES, "UTF-8");
}
Upvotes: 0