attentionjay
attentionjay

Reputation: 55

How to enter form data into a mysql database using an array?

I have a form that submits steps and ingredients for recipes that I am practicing with for another project. I have set the form up to submit the data in an array, but I can't get the PHP code correct to insert the data into the database. I have pasted the form layout here. The form comes up as part of another PHP page that is called when the user enters a recipe name to add to the database. I would like to have 10 separate step entries on this form if I can figure out how to insert them correctly into the database.

<form action="add_recipe2.php" method="post">
    <fieldset>
        <legend>Add a Recipe</legend>
        <table>
            <tr>
                <td>Recipe Name:</td>
                <td><input type="text" name="recipename" value="$recipename"></td>
           </tr>
            <tr>
                <td>Step:</td>
                <td><input type="text" name="recipe[0][step]" placeholder="1"></td>
                <td>Ingredients:</td>
                <td><input type="text" name="recipe[0][ingredients]" placeholder="Ingredients"></td>
            </tr>
            <tr>
                <td>Step:</td>
                <td><input type="text" name="recipe[1][step]" placeholder="2"></td>
                <td>Ingredients:</td>
                <td><input type="text" name="recipe[1][ingredients]" placeholder="Ingredients"></td>
            </tr>
            <tr>
                <td>Step:</td>
                <td><input type="text" name="recipe[2][step]" placeholder="3"></td>
                <td>Ingredients:</td>
                <td><input type="text" name="recipe[2][ingredients]" placeholder="Ingredients"></td>
            </tr>

        </table>
        <button type="submit">Add a Recipe</button>
        <button type="reset">Reset</button>

    </fieldset>
</form>

This is the PHP that enters the data into the database. The problem is when I only add two records to the database the last record still inserts, but it inserts a blank line. I need a way to only add the data that is being passed from the form even if it is only one line. I have researched this a long time and this represents one of the answers that I found. However, it still does not stop inserting into the database when there is no more data from the form.

$recipename = $_REQUEST["recipename"];

$conn = mysql_connect("localhost","user","password") or die(mysql_error());
mysql_select_db("test");

foreach($_POST['recipe'] as $recipe) { 

// Add to database
$sql1 = "INSERT INTO `recipes` (recipe, step, ingredients) VALUES   ('".$_POST['recipename']."', '".$recipe['step']."', '".$recipe['ingredients']."')";
mysql_query($sql1, $conn) or die(mysql_error());
 } //end foreach

I just can't figure this out. I need help. I suspect that I have to have a way to tell how many records I am actually sending if it is not the number of form entries that exist.

Upvotes: 0

Views: 916

Answers (2)

Elias Dorneles
Elias Dorneles

Reputation: 23796

The fact is, even if the user doesn't fill in the information in the form for recipe[3], the empty values are still being submitted.

You have to validate your data before insert into the database:

function isValidRecipe($recipe){
    // returns true if ingredients and step are not empty
    return !(empty($recipe['ingredients']) || empty($recipe['step']));
}
foreach($_POST['recipe'] as $recipe) {
if (isValidRecipe($recipe)){
    // Add to database
    $sql1 = "INSERT INTO `recipes` (recipe, step, ingredients) VALUES ('".$_POST['recipename']."', '".$recipe['step']."', '".$recipe['ingredients']."')";
        mysql_query($sql1, $conn) or die(mysql_error());
    }
}

Note that this is the minimum validation, you should probably check everything more thoroughly.

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270599

You will need to test if values in the array component are filled in before querying them. Also, you MUST escape all the insert values against SQL injection with mysql_real_escape_string():

$recipename = mysql_real_escape_string($_POST['recipename']);

foreach($_POST['recipe'] as $recipe) { 
  // Only insert if step is non-empty.
  if (!empty($recipe['step']) {
    // Add to database

    // Escape against SQL injection
    $recipe['step'] = mysql_real_escape_string($recipe['step'];
    $recipe['ingredients'] = mysql_real_escape_string($recipe['ingredients'];

    $sql1 = "INSERT INTO `recipes` (recipe, step, ingredients) VALUES   ('".$recipename."', '".$recipe['step']."', '".$recipe['ingredients']."')";
    mysql_query($sql1, $conn) or die(mysql_error());
  }
} 

Upvotes: 2

Related Questions