0

I am fairly new to php and I am wondering how to loop through a dynamically created form so that I can input whatever is input into the form into my database--so it appears something is wrong with my code. So, measurement and foodid are integers and unitMeasurement is a string from a select option form type.

<?php
if ($_POST['formSubmit'] == 1) {

  $measurement = $_POST['measurement'];
  $foodid = $_POST['foodid'];
  $unitMeasurement = $_POST['unitMeasurement'];
  if($result){
    $recipeid = mysql_insert_id();
    }

  $i = 0;
  while($i < sizeof($measurement)){
    $query = "INSERT INTO recipeItems (`userid`, `foodid`, `itemMeasurement`, `itemMeasurementUnit`, `recipeid`) VALUES (".$_SESSION['userid'].",".$foodid[$i].",".$measurement[$i].",'".$unitMeasurement[$i]."',".$recipeid[$i].")";
    mysql_query($query);
    $i++;
  }
}

?>

Here is what $result is:

    $sql = "INSERT INTO recipes (`userid`, `rname`) VALUES (".$_SESSION['userid'].",'".$recipeName."')";

$result = mysql_query($sql); 
PuddingCat
  • 45
  • 3
  • http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – Matt Mar 09 '16 at 05:09
  • http://stackoverflow.com/questions/134099/are-pdo-prepared-statements-sufficient-to-prevent-sql-injection?rq=1 – Matt Mar 09 '16 at 05:12

1 Answers1

0

Moving past mkaatman pointing out it is bad practice to use mysql_*() functions in PHP, let's look at your problem.

First of all, you can loop over posted values from an arbitrary form like so:

<?php

foreach ($_POST as $key => $value) {
    //key is the lookup value
    //value is the actual posted value
}

without providing more information, we can't help you any more than that.

As far as your provided code, $result is not defined anywhere in your provided code, so either we can assume that the if-statement will never execute or we can guess that it will.

If the if-statement block is executed, then mysql_insert_id() will not work, as it can only return the id of an inserted item AFTER it has been inserted, i.e. it would have to be called after mysql_query().

Also, given you are creating a query out of concatenated-string (which is very bad practice, alongside moving away from mysql_*() functions, you should also look into prepared statements), you will need to wrap anything that is a string in quotations.

Beyond that, there isn't enough information to properly provide assistance, if this doesn't help, you will need to provide more code.

Damon Swayn
  • 1,326
  • 2
  • 16
  • 36