These two fields are inserted into a database. However, I want to give the user the ability to "Add another item". They should be able to, ideally, add as many items as they like. When they submit the form, the data would be inserted into a mysql table.
How can I go about doing this? Creating 10 extra columns in my database to accommodate extra items being added does not sound realistic nor ideal.
Thanks for the help!
Here is a snippet of my code, where I insert my data into the DB:
if ($stmt = $mysqli->prepare("INSERT items (number, description) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $number, $description);
$stmt->execute();
$stmt->close();
}
This is a pretty complex question, but there are some pretty straightforward solutions. First off, you'll need to change the back-end PHP script that you use to handle having a variable number of items.
For example, right now, you probably have something like:
$item_number = $_POST['item_number'];
$item_description = $_POST['item_description'];
add_item_to_db($item_number, $item_description);
You'll need to change your code to handle the processing of an array of items:
$item_numbers = $_POST['item_number'];
$item_descriptions = $_POST['item_description'];
// validate that count($item_numbers) == count($item_descriptions)
for ($i = 0; $i < count($item_numbers); $i++) {
add_item_to_db($item_numbers[$i], $item_descriptions[$i]);
}
There's quite a bit of error handling that you'll need to perform above that's not shown. If the user enters a different number of item_numbers than item_descriptions, you'll have to determine how to handle that. Also, any of the fields may be blank. Some cases may be errors, others perhaps not.
You'll have to change your HTML:
<input type="text" name="item_number[]" />
<input type="text" name="item_description[]" />
Note the [] in the name. That specifies an array of values for each.
Finally, you'll need to dynamically add a new set of input items on the screen when the user presses the Add another item link. I would recommend using jQuery for this. To accomplish this you would do something like:
jQuery('<input type="text" name="item_number[]" /><input type="text" name="item_description[]" />').appendTo('#someDiv');
Ensure that the new input elements are appended inside the form element. Obviously, there is a lot of code left to be written. This is just a basic example of the concepts.
Just use :
name="item[]"
for item # '
and
name="description[]"
<input type="text" name="item[]" /><input type="text" name="description[]" />
For item description field and in your server side iterate through both of them.
in the front end just create a script that duplicate that node many times.
EDIT
Based in the code you showed it should be something similar to the below code :
if(isset($_POST['item']){
for($i = 0; $i < count($_POST['item']); $i++){
$number = $_POST['item'][$i];
$description= $_POST['description'][$i];
if ($stmt = $mysqli->prepare("INSERT items (number, description) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $number, $description);
$stmt->execute();
$stmt->close();
}
}
In your javascript do like below:
function addRow(){
document.getELementById('container').el.innerHTML += '<input type="text" name="item[]" /><input type="text" name="description[]" />' ;
}
HTML Code:
<form name='myform' >
<div id="container">
<input type="text" name="item[]" /><input type="text" name="description[]" />
</div>
<p onclick="addRow() ;" >Add another item</p>
</form>
I hope this helps.
UPDATE
Try this one :
if(isset($_POST['item']){
if ($stmt = $mysqli->prepare("INSERT items (number, description) VALUES (?, ?)"))
{
for($i = 0; $i < count($_POST['item']); $i++){
$number = $_POST['item'][$i];
$description= $_POST['description'][$i];
$stmt->bind_param("ss", $number, $description);
$stmt->execute();
}
$stmt->close();
}
Related
I am setting up a system that has many answers from a question. Therefore the user can click a button to dynamically add answers. I want the user to be able to tick a checkbox next to the answers which are correct and then insert this into the database (1 being correct).
Here is what I have:
HTML:
<div id="answers">
<label class="answer">
Answer:
<input type="text" name="ab_name[]" value=""/>
Correct?
<input type="checkbox" name="ab_correct[]" value="0">
</label>
</div>
PHP
$ab_name = $_POST['ab_name'];
$ab_correct = $_POST['ab_correct'];
$sql = "INSERT INTO answers_bank (`ab_name`, `ab_correct` ) VALUES (:ab_name, :ab_correct )";
$stmt = $db->prepare($sql);
foreach ($_POST['ab_name'] as $ab_name) {
$stmt->bindValue(':ab_name', $ab_name);
$stmt->bindValue(':ab_correct', $ab_correct);
$stmt->execute();
}
Like this:
The SQL inserts the ab_name but the ab_correct is ALWAYS set to 1 if it is ticked or unticked. Any guidance on this please?
You could use a for loop instead of the foreach. Well, first of all, you need to make sure both arrays has the same amount of elements.
if(count($_POST['ab_name']) != count($_POST['ab_correct']))
exit('Not same amount of elements.');
Then, loop through each of them.
for($i=0; $i<count($_POST['ab_name']); $i++){
$stmt->bindValue(':ab_name', $_POST['ab_name'][$i]);
$stmt->bindValue(':ab_correct', $_POST['ab_correct'][$i]);
$stmt->execute();
}
if(isset($_POST['$ab_correct'])){$update = 1;}else{$update = 0;}
foreach ($_POST['ab_name'] as $ab_name) {
$stmt->bindValue(':ab_name', $ab_name);
$stmt->bindValue(':ab_correct', $update);
$stmt->execute();
}
I am having a hard time wrapping my head around the foreach construct. I have found numerous examples of course, but I never seem to be able to adapt them to my needs.
Please consider this working example I have:
I am collecting two dates in an HTML form:
<form method="post">
<legend>Minutes and Records</legend>
<label for="FirstAGMDate">First AGM Date (only if known)</label>
<input type="text" name="FirstAGMDate" value="2014-01-01" />
<label for="MinutesInspectedFromDate">Minutes Inspected From Date</label>
<input type="text" name="MinutesInspectedFromDate" value="2014-01-02" />
<input type="submit" name="submit" />
</form>
On submit the values are being pushed to the mysql database with a PDO prepared statement:
if (isset($_POST['submit'])) {
$sql = "UPDATE jobsinglevalues SET Date = :FirstAGMDate WHERE FormId = 0;
UPDATE jobsinglevalues SET Date = :MinutesInspectedFromDate WHERE FormId = 1;";
$sth = $db->prepare($sql);
$sth->execute(array(':FirstAGMDate'=>($_POST['FirstAGMDate']), ':MinutesInspectedFromDate'=>($_POST['MinutesInspectedFromDate'])));
}
This works no problem, but it's not very clever when I need to repeat this for a dozen inputs. What I want to do is achieve this with only one line of sql; looping for each <input type="text" name="Value" />.
How can I place this into a foreach loop?
In my head it works like this:
On submit each input updates the value in the database based on FormId, which increments by 1 each loop starting at 0. FormId is not a primary key, it simply mirrors the order in which the form elements are displayed.
Update - working example
if (isset($_POST['submit'])) {
$FormId = 0;
foreach($_POST['Value'] as $avalue){
$sql = "UPDATE jobsinglevalues SET Date = :Value WHERE FormId = :FormId";
$sth = $db->prepare($sql);
$sth->execute(array(':Value'=>($avalue), ':FormId'=>($FormId)));
++$FormId;
}
}
This seems to logically work to me! Is the correct solution similar? Please let me know if I need to clarify anything.
Thankyou,
Sam
Let's start by making sure all our values are in an array after posted; if you don't care about the keys you can just use name="Values[]", but I'll use name="Value[FirstAGMDate]" etc so we know what key a value belongs to.
<form method="post">
<legend>Minutes and Records</legend>
<label for="FirstAGMDate">First AGM Date (only if known)</label>
<input type="text" id="FirstAGMDate" name="Value[FirstAGMDate]" value="2014-01-01" />
<label for="MinutesInspectedFromDate">Minutes Inspected From Date</label>
<input type="text" id="MinutesInspectedFromDate" name="Value[MinutesInspectedFromDate]" value="2014-01-02" />
<input type="submit" name="submit" />
</form>
Now we can process the posted array of values. If we want to do something with the key, we can use foreach($_POST['Value'] as $akey => $avalue), if we are only interested in the values then foreach($_POST['Value'] as $avalue) suffices.
$sql = "UPDATE jobsinglevalues SET Date = :Value WHERE FormId = :FormId;";
$sth = $db->prepare($sql);
foreach($_POST['Value'] as $akey => $avalue) {
$sth->execute(array(':Value' => $avalue, ':FormId'=> $FormId ));
++$FormId;
}
[edit] As per edit-suggestion by #AravindKishore, creating the prepared statement is better done before the loop. Prepare once, enjoy forever.
I have a registration form that allows a user to register as many people as they want. For example I don't know ahead of time if 1 person is registering or if 500 are. So on the server side if I have 3 people registering at once I need to access all the first names of a person by $_POST['first0'] $_POST['first1'] and $_POST['first2']. So here is my database query.
for ($i=0; $i < runners; $i++) {
$query = "INSERT INTO ".$usertable." VALUES (".$_POST['first'.$i].", ".$_POST['last'.$i].", ".$_POST['age'.$i].",
".$_POST['gender'.$i].", ".$_POST['email'.$i]." , ".$_POST['phone'.$i]." , ".$_POST['address'.$i]." ,
".$_POST['city'.$i]." , ".$_POST['state'.$i]." , ".$_POST['zip'.$i]." , ".$_POST['type'.$i]." , ".$_POST['tshirt'.$i].")";
My query is not working so I know my quotes and apostrophes are incorrect would anyone be able to show me the correct way to accomplish this. Any help is appreciated!
First of all, posted data is a lot easier to work with if your form entries use the array syntax, i.e.:
<label>First: <input name="first[]" value="" /></label>
<label>Last: <input name="last[]" value="" /></label>
<label>Age: <input name="age[]" value="" /></label>
<label>Gender:
<input type="radio" name="gender[]" value="m" />Male
<input type="radio" name="gender[]" value="f" />Female
</label>
Then, in your code, values like $_POST['first'] are an array of values.
Secondly, you should look at prepared statements. Observe:
$stmt = $db->prepare('INSERT INTO mytable (first, last, age, gender) VALUES (?, ?, ?, ?)');
foreach ($_POST['first'] as $index => $value) {
$stmt->execute(array(
$value,
$_POST['last'][$index],
$_POST['age'][$index],
$_POST['gender'][$index],
));
}
First of all, you should prevent SQL injection while interacting with database.
Use mysqli_real_escape_string. Here is the updated query.
for ($i=0; $i < runners; $i++) {
$firstname = mysqli_real_escape_string($_POST['first'.$i]);
$lastname = mysqli_real_escape_string($_POST['last'.$i]);
$age = mysqli_real_escape_string($_POST['age'.$i]);
$gender = mysqli_real_escape_string($_POST['gender'.$i]);
$email = mysqli_real_escape_string($_POST['email'.$i]);
$phone = mysqli_real_escape_string($_POST['phone'.$i]);
$address = mysqli_real_escape_string($_POST['address'.$i]);
$city = mysqli_real_escape_string($_POST['city'.$i]);
$state = mysqli_real_escape_string($_POST['state'.$i]);
$zip= mysqli_real_escape_string($_POST['zip'.$i]);
$type= mysqli_real_escape_string($_POST['type'.$i]);
$tshirt= mysqli_real_escape_string($_POST['tshirt'.$i]);
$query = "INSERT INTO ".$usertable." VALUES ('".$firstname."', '".$lastname ."', ".$age .",
'".$gender ."', '".$email ."', ".$phone." , '".$address ."' ,
'".$city."' , '".$state."' , ".$zip." , '".$type."' , '".$tshirt."')";
The better way to do this is instead of using user0, user1, user2, ...
You can actually past the html input text as an array.
e.g:
<!-- first user field -->
<input type="text" name="users[]" />
<!-- second user field -->
<input type="text" name="users[]" />
<!-- third user field -->
<input type="text" name="users[]" />
So your php will look something like this:
$users = $_POST['users'];
foreach ($users as $user) {
insertQuery = "INSERT INTO $userTable VALUES ('".mysqli_escape_string($user)."');
}
Of course the code above is only an example with 1 variable you can apply them to all other variables.
Cheers.
As suggested by #plain jane you are missing a lot of single quotes.
You can use PHP's variable replacement capability like the following. This is much more readable code.
$query = "INSERT INTO $usertable VALUES ('{$_POST['first'.$i]}', '{$_POST['last'.$i]}', '{$_POST['age'.$i]}',
'{$_POST['gender'.$i]}', '{$_POST['email'.$i]}', '{$_POST['phone'.$i]}', '{$_POST['address'.$i]}' ,
'{$_POST['city'.$i]}' , '{$_POST['state'.$i]}' , '{$_POST['zip'.$i]}' , '{$_POST['type'.$i]}' , '{$_POST['tshirt'.$i]}')";
Warning: Your code is vulnerable to SQL injection and can be easily broken with just a single quote in any posted field. even St'Mary as first name will break your code. To prevent this
Please validate/sanitize your posted values
Use Prepared statements instead of direct query string.
I if have inputs like this one, but those 2 inputs are repeating themselves multiple times. So it could be:
<input name="Gpodaciogolubu[]" type="text">
<input name="Gpodaciogolubu_godina[]" type="number">
<input name="Gpodaciogolubu[]" type="text">
<input name="Gpodaciogolubu_godina[]" type="number">
<input name="Gpodaciogolubu[]" type="text">
<input name="Gpodaciogolubu_godina[]" type="number">
...
Is it possible to use while or foreach loop to get both values at the same time and insert it both in database like:
"INSERT INTO database (field1, filed2) VALUES ('$_POST["Gpodaciogolubu"]','$_POST["Gpodaciogolubu_godina"]')"
I'm coding in PHP/MySQL
First build an array of rows to insert:
$rows = []; // or array() in PHP 5.3 and older
$l = count($_POST['Gpodaciofolubu']);
for( $i=0; $i<$l; $i++) {
$rows[] = "("
."'".mysql_real_escape_string($_POST['Gpodaciofolubu'][$i])."', "
.intval($_POST['Gpodaciofolubu_godina'][$i]) // since you have `type="number"`
.")";
}
Then batch insert them:
mysql_query("insert into `database` (`field1`, `field2`) values ".implode(",",$rows));
This assumes, of course, that you're using the mysql extension. This assumption is based on the complete lack of any attempt to sanitize your input.
I have the following code that I created to update the database with the data coming from a a php form. $_POST['variables'] are different arrays.
the issue I am having is when I echo $updater the field status and the field display values are not in the correct order. for example if I check the checkbox 3. it will return the value enabled on the first line of the results. any suggestions would help thank you
//update data
$priority = $_POST['priority']; // this will be an array
$enable = $_POST['enable'];
$height = $_POST['height'];
$position = $_POST['position'];
$widgetid = $_POST['widgetid'];
$display = $_POST['display'];
$i = -1;
foreach($priority as $priori)
{
++$i;
$row_enable = $enable[$i];
$row_height = $height[$i];
$row_prio = $priority[$i];
$positio = $position[$i];
$disp = $display[$i];
$widgeti = $widgetid[$i];
if (isset($enable[$i]))
$enables ="y";
else
$enables ="n";
if (isset($display[$i]))
$displ = "y";
else
$displ = "n";
//DO THIS FOR THE REST AND THEN YOUR UPDATE QUERY
$updater = "UPDATE hpoptions SET position='$positio', height='$row_height', status='$enables', display='$displ', priority='$row_prio' WHERE userid='$ud' and widgetid='$widgeti'";
echo $updater."<br>";
} // ends here
There is no guarantee you will get your arrays in the desired order, unless you force it in the HTML. You probably have something like this:
<input type="text" name="position[]">
<input type="text" name="height[]"> ...
<input type="hidden" name="widgetid[]" value="w1">
...
<input type="text" name="position[]">
<input type="text" name="height[]"> ...
<input type="hidden" name="widgetid[]" value="w2">
...
You need to add an extra dimension to the arrays encoded on the field name. You need an unique id for each field group, and I believe your widgetid is exactly that, right? So you can do:
<input type="text" name="data[w1][position]">
<input type="text" name="data[w1][height]"> ...
...
<input type="text" name="data[w2][position]">
<input type="text" name="data[w2][height]"> ...
...
Notice you don't even need a field called widgetid anymore, since the ids will be encoded on every field name. In PHP, you do this to loop through the results:
foreach($_POST['data'] as $widgetid => $data) {
// Make sure to check if the values won't make your SQL query vulnerable to injection!
// http://stackoverflow.com/questions/332365/xkcd-sql-injection-please-explain
$widgetid = mysql_real_escape_string($widgetid);
$position = is_numeric($data['position']) ? $data['position'] : 0;
// ...
// Build your update query here
}