3

I am trying to look through some input fields in a form and add them to a database. The user sets the number of fields, so I can't do something like the code below because there is no specific number of fields.

for($i=0; $i<(number-of-fields); $i++)
{
    $_REQUEST['Question+$i']
}

I have tried this as well:

<?php
$con=mysqli_connect("","test","test","Flashcards");

foreach($_REQUEST['Question[]'] as $value)
    {
    $newcards="INSERT INTO Cards(Questions)
    VALUES($value)";
    mysqli_query($con,$newcards);
    }

mysqli_close($con);
?>

It just doesn't add anything to my database. How should I go about doing this? I am new to PHP and SQL and can't seem to figure this out.

3 Answers 3

6

Given:

<input type="text" name="foo[]" />
<input type="text" name="foo[]" />
etc...

in your form, you'd loop over them with

foreach($_POST['foo'] as $index => $value) {
    ...
}

The [] in the field name will be stripped off by PHP and used as a hint that it should expect multiple values with the same name, causing it to create a sub-array inside $_GET/$_POST to accomodate those extra values.

You can also suggest which array keys PHP should use, e.g.

<input type="text" name="foo[1]" value="hi there" />
<input type="text" name="foo[abc]" value="TGIF!" />

echo $_POST['foo'][1]; // outputs "hi there"
echo $_POST['foo']['abc'] // outputs "TGIF!"

Multi-dimensional arrays are also supported, using the same notation/access methods.

Sign up to request clarification or add additional context in comments.

7 Comments

I am confused about how I am supposed to add each one to the database now... I tried VALUES('$_POST[foo[$index]]'), but that simply doesn't work. How do I do this?
this would be more like insert into CARDS (questions) VALUES($value) check us1.php.net/manual/en/control-structures.foreach.php and look at the foreach($array as $k=>$v) examples.
you really really REALLY need to learn about SQL injection attacks before you try ANYTHING related to a database in PHP (or any other language)
This is what I tried the first time and it didn't work, but I went back and added apostrophes around the $value and it seems to be functioning properly, so thanks.
@Marc B I know about SQL injections. Security is not a concern in what I am currently doing. I'm just messing around with databases and server-side languages right now. In this particular instance, I have a flash card program. The use of MySQL here is to allow users to save cards to their own database.
|
2

you can assign input names like he following(using javascript) and create a hidden field that contains the number of field, so when the user add more input fields, the hidden field is updated dynamically.

<input name="field_1">
<input name="field_2">
<input name="field_3">
<input type="hidden" name="count" value="3">

so when you post this you know how many fields you have.

Comments

1

OK.

  1. First of all, $value is never defined.

  2. This code is a security risk because you need to sanitize your input before inserting into the database.

  3. use $_GET or $_POST depending on how your form is set. $_REQUEST probably also includes information you wont need

  4. Not sure what your database looks like. Should each form field be a separate row or a separate column? Your code seems to do the former, but it sounds like you'd want the latter? If it's the latter then you really would need to name your form inputs like Amir Noori noted.

    Assuming you have a form like that:

    <form method="POST" action="myphp.php`>
    <input type="text" name="column_name_one" />
    <input type="text" name="column_name_two" />
    <input type="text" name="column_name_three" />
    <input type="submit" name="submit" value="submit" />
    

then

     <?php  
     if (isset $_POST['submit'] {
      $con=mysqli_connect("","test","test","Flashcards");
    
      $values = array();
      $columns = array();
      foreach($_POST[] as $key => $value) {
           if (!empty($key) && $key != "submit") {
             $values[] = $con->real_escape_string($value);
             $columns[] = $con->real_escape_string($key);
            }
      }
      $colStr = implode(",",$columns);
      $valStr = implode("','",$values);
      $myQuery = "INSERT INTO Cards($colStr) VALUES ('$valStr');
      if (!$con->query($myQuery)) {
         echo "Error Occured:  $con->error";
      }
    }
    ?>

Now this only works when your column names are the same as your form input names. Also assumes they are all strings (varchar etc). If this is not the case then you need to handle that by simply accessing the form fields individually by name. One simple way:

       <?  
          
          if (isset($_POST['name']) && !empty($_POST['name']) {   //name field maps to cName column varchar
            $colStr = "cName,";
            $valStr = "'" . $_POST['age'] . "',";  //need quotes
          }

          if (isset($_POST['age']) && !empty($_POST['age']) {   //age field maps to customerAge column numeric
            $colStr .= "customerAge,";
            $valStr .= $_POST['age'] . ",";       //no quotes
          }          
        ?>

Or use array_map() to map an array of column names to form fields. Something like that might also help if you need to make sure all the post variable names are really valid column names and someone isn't trying to send you garbage. Obviously the insert will fail if the column names aren't correct but usually it's better not to let it even try to insert a bad query.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.