Heloo everyone. I have this code for a form in PHP...but when I use $POST['collection'] or any other from th drop down lists I cannot access the vaalue of the variable passed:

<form enctype="multipart/form-data" action="insert_validation.php" method="post">
<table border="0">
<tr><th>Choose category:
<tr><td><select name="category">

<?php
$sql=mysql_query('SELECT category from Category order by category');
$numRows = mysql_num_rows($sql);
for ($i = 1; $i <= $numRows; $i++) 
{
    $crtRow = mysql_fetch_array($sql);
    $idCat = $crtRow["idCategory"];
    $cat = $crtRow["category"];
    print("<option value=\"$idCat\">$cat</option>");
}
?>


</select>
<tr><th>Choose collection:
<tr><td><select name="collection">

<?php
$sql=mysql_query('SELECT collection from collection order by collection');
$numRows = mysql_num_rows($sql);
for ($i = 1; $i <= $numRows; $i++) 
{
    $crtRow = mysql_fetch_array($sql);
    $idCol = $crtRow["idCollection"];
    $coll = $crtRow["collection"];
    print("<option value=\"$idCol\">$coll</option>");
}
?>
<tr>
<input type="hidden" name="collection" value="<?php print("$idCol");?>">
<input type="hidden" name="ins" value="Insert">
</select>



<tr><th>Choose metal type:
<tr><td><select name="metal">

<?php
$sql=mysql_query('SELECT metal from MetalType order by metal');
$numRows = mysql_num_rows($sql);
for ($i = 1; $i <= $numRows; $i++) 
{
    $crtRow = mysql_fetch_array($sql);
    $idMet = $crtRow["idMetalType"];
    $met = $crtRow["metal"];
    print("<option value=\"$idMet\">$met</option>");
}
?>

</select>

<tr><th>Choose stone:
<tr><td><select name="stone">

<?php
$sql=mysql_query('SELECT stone from stone order by stone');
$numRows = mysql_num_rows($sql);
for ($i = 1; $i <= $numRows; $i++) 
{
    $crtRow = mysql_fetch_array($sql);
    $idSt = $crtRow["idStone"];
    $st = $crtRow["stone"];
    print("<option value=\"$idSt\">$st</option>");
}
?>

<tr>
<td>Model: </td><td><input type="text" name="model" /> </td>
</tr>
<tr>
<td>Picture </td><td><input type="text" name="picture" /></td>
</tr>
<tr>
<td>Stock: </td><td><input type="number" name="stock" /> </td>
</tr>
<tr>
<td> Price </td><td><input type="(float)number" name="price" /></td>
</tr>
</table>

<input type="submit" name= "ins" value="Insert" />
</form>

<

Please post the insert_validation.php script also since the values should be accessible there (assuming that the queries return expected values).

I don't know if it was a typo on the post, but it's $_POST and not $POST.

Another thing, I'm guessing, but I don't hink <input type="(float)number" name="price" /> is a valid markup.

This is the php code for insert_validation.php

<?php

echo '<font size="4" face="Calambria" >';

$con = mysql_connect("localhost","root");
if (!$con)
  {
    die('Could not connect: ' . mysql_error());
  }



mysql_select_db("jewelry", $con);


if(!$_POST['model'] or !$_POST['price'] or !$_POST['picture'] or !$_POST['stock']) 
    {
            echo '<a href="insert.php">Back to insert page</a><br><br>';
            die('You did not complete all required fields');
    }   


$mod = $_POST['model'];
$pr = $_POST['price'];
$pic = $_POST['picture'];
$stoc=$_POST['stock'];
$idCol=$_POST['collection'];
$idCat=$_POST['category'];
$idMet=$_POST['metal'];
$idSt=$POST['stone'];


$check1 = mysql_query("SELECT model FROM Jewelry WHERE model='$mod'") or die ('Cannot perform Query');
$result1 = mysql_num_rows($check1);
if ($result1 > 0) 
       {
        echo '<a href="insert.php">Back to insert page</a><br>';
        die('Sorry, the model '.$mod.' already exists.');
        }

if($pr<=0)
{
     echo '<a href="insert.php">Back to insert page</a><br>';
        die('Sorry, invalid price');
}

$check2 = mysql_query("SELECT picture FROM Jewelry WHERE picture='$pic'") or die ('Cannot perform Query');
$result2 = mysql_num_rows($check2);
if ($result2 > 0) 
        {
        echo '<a href="insert.php">Back to insert page</a><br>';
        die('Sorry, the picture'.$pic.' already exists.');
        }

$sql="INSERT INTO Jewelry (model, price, picture, stock, idCollection, idMetalType, idCategory, idStone) VALUES
('$_POST[model]','$_POST[price]','$_POST[picture]','$_POST[stock]','$_POST[collection]','$_POST[metal]','$_POST[category]','$_POST[stone]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }

echo '</font>';
mysql_close($con);
?>

Another thing, I'm guessing, but I don't hink <input type="(float)number" name="price" /> is a valid markup

It definately isn't. This is HTML code and HTML does not have a cast function and casting number attribute is not logical anyway. It must be a typo.

The number attribute is HTML5 feature, it did not exist in (X)HTML 4.x.

We have to check first whether all the values are in the $_POST. Can you please stick this code on line 21 and post the result:

die(print_r($_POST, 1));

Ok. Thank you:). And if you don't mind,what do you think about the error that appears when I try to insert a new item in the database?

Error: Cannot add or update a child row: a foreign key constraint fails (jewelry.jewelry, CONSTRAINT fk_Jewelry_Collection1 FOREIGN KEY (idCollection) REFERENCES collection (idCollection) ON DELETE NO ACTION ON UPDATE NO ACTION)

On lines 23 to 30 you assign $_POST values to variables but then you do not use those variables in the query on line 55. Is there any reason for that?

This is the result:)

Array ( [category] => [collection] => [ins] => Insert [metal] => [stone] => [model] => A00001 [picture] => image.jpeg [stock] => 54 [price] => 464 )

I tried to print the values of the $_POST variablesto see if they are correct and I forgot to delete them:D

I guess there is a problem in the drop lists....but I' not sure

In the above output the values for category, collection and stone are missing (not set) and that is why the query can not get constructed correctly on line 55. The good practice is to check for existance of values of $_POST array before assigning them to variables. At the same time at least escape the values so you do not get SQL injection attack.

if(isset($_POST['model'])) {
    $mod = mysqli_real_escape_string($_POST['model']); // example for mysql
} else {
    $mod = '';
}
...

You can also do it with less code using ternary operator:

$mod = isset($_POST['model'] ? mysqli_real_escape_string($_POST['model']) : '';

Or maybe is better to make sure users fill-in/select all fields before submitting a form. In this case you have to do javascript checking in the page with the form and checking and validating on the processing page.

Thanks for your advices:)

And do you have any idea why the $_POST values are not set? :-S

Have you selected all fields when testing?

One of the reasons might be the enctype attribute on line 1. Can you change it to application/x-www-form-urlencoded (which is default for forms) or just omit it (since it is default). The multipart/form-data value is used for file upload. It does not encode the url characters.

And correct the code on line 83 to:

<input type="number" name="price" />

as AleMonteiro suggested in his post above.

Also check all the queries in phpmayadmin whether they return the correct values for select elements:

SELECT category from Category order by category
SELECT collection from collection order by collection
SELECT metal from MetalType order by metal
SELECT stone from stone order by stone

Also you have errors in HTML code:

  • closing </select> tag should be after line 33 and not on line 37
  • </td></tr> is missing before line 34
  • etc ...

You editor should warn you about the html errors (if it is not notepad). Or you can have look at the source in Firefox (rigt click on page and select View page source). The errors should be marked red.

Please correct the html errors first since they render elements incorrectly.

providing values to drop down list use like as follows

  <?
     // php code that gets data for drop down list
  ?>

    <option value= "<? dropdown data?> "> <? dropdown data?>  </option>  

  <?
     // remaining code

  ?>

instead of
print("<option value=\"$idCat\">$cat</option>");

and check your answer by replacing this way
and let me know the status of your code

@radhakrishna.p

print("<option value=\"$idCat\">$cat</option>"); is completely valid code (if you meant line 14 above).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.