I am trying to pass 2 arrays in a MYSQL table using HTML array, I want to insert both values in the same row at the same time of the loop, of course nested loop isn't going to work, the first input value passed successfully, but the second input inserts wrong & unrelated values. I am sure it's because the for loop logic is incomplete, but I can't seem to adjust properly. any help will be appreciated.
HTML (...html code inside PHP then this, $row['id'] is the value that shall be passed to POST):
<input type="text" id="mytextbox" name="comment[]" placeholder = "Add your comments here" required>
<input type="text" id="mytextbox" list="decision[]" name="decision" placeholder = "Choose your decision" required>
<datalist id="decision[]">';
echo '<option value="'.htmlspecialchars($row['id']).'">'.htmlspecialchars($row['name']).'</option>';
<input type="text" id="mytextbox" name="comment[]" placeholder = "Add your comments here" required>
<input type="text" id="mytextbox" list="decision[]" name="decision" placeholder = "Choose your decision" required>
<datalist id="decision[]">';
echo '<option value="'.htmlspecialchars($row['id']).'">'.htmlspecialchars($row['name']).'</option>';
<input type="text" id="mytextbox" name="comment[]" placeholder = "Add your comments here" required>
<input type="text" id="mytextbox" list="decision[]" name="decision" placeholder = "Choose your decision" required>
<datalist id="decision[]">';
echo '<option value="'.htmlspecialchars($row['id']).'">'.htmlspecialchars($row['name']).'</option>';
PHP (after successful POST of $comment as input(1) & $decision as input(2) and working queries):
for ($i=0;$i<count($comment);$i++){
$query = "INSERT INTO table (otherid,col1,col2) VALUES ('$otherid','$comment[$i]','$decision[$i]')";
$result = $dbc->query($query);
}
You are getting only the last decision, because you did not use square brackets in the field name, as you did with the comments field. name="decision" needs to be name="decision[]". Only then will PHP create an array out of multiple passed parameters of the same name; without square brackets, they simply overwrite each other.
The duplicate IDs are only of client-side importance - selecting from those lists, will likely not populate the correct input field, but it has little to do with what actually gets submitted, if you filled those fields by hand. But you should be able to make thos IDs dynamic, for example by appending the row ID.
<datalist id="decision-123">, with a matching list="decision-123" on the input field.
Related
I'm not sure how to ask this question. It procedural question I believe.
<input type="hidden" name="1[]" value="dummy">
<input type="radio" name="1[]" value="5">
<label> Very Good </label>
<input type="radio" name="1[]" value="4">
<label> Good </label>
<input type="text" name="1[]" size="20">
<br>
<input type="hidden" name="2[]" value="dummy">
<input type="radio" name="2[]" value="5">
<label> Very Good </label>
<input type="radio" name="2[]" value="4">
<label> Good </label>
<input type="text" name="2[]" size="20">
$_POST output:
[1] => Array
(
[0] => Text misc
)
[2] => Array
(
[0] => 5
[1] =>
)
From this I construct and INSERT statement.
INSERT INTO coached_tracked (coached_id, value, note)
VALUES ($key, $value[0], $value[1]);
This is are dynamically generated form inputs. A radio button, text field pair.
How can I handle an occurrence where the radio is not selected and the text field has value, like in the first instance. I want the option of having nothing selected so a default value seems not called for. I tried with both with and without a dummy value (I saw an example suggesting a hidden field as a possible solution.)
Suggestions.
You should not tell the database what ID to use. Let the database itself determine that by using an auto-incremented column.
First, start with a logical input name. Using just numbers is extremely confusing and looking at your code, I have absolutely no idea what you're doing. We also want everything to go into the same PHP $_POST variable to not have to iterate over all possible number cominations. That means we can just iterate over the one single array.
Let's say you're adding a coach to a database, so logically we would start with:
<input name="coach">
Now when we want to add multiple coaches instead of just one, we can use HTML array names, however I would recommend you hard-code them instead of auto-incrementing in your HTML, which should simplify things later on. We also pluralize it to coaches:
<?php
for ($i=0;$i<10;$i++) {
?>
<input name="coaches[<?=$i?>]">
<?php
}
Now if each coach contains a certain properties, let's say name, salary, note, etc, we can add the properties to the input names like so:
<?php
for ($i=0;$i<10;$i++) {
?>
<input name="coaches[<?=$i?>][name]">
<input name="coaches[<?=$i?>][salary]">
<input name="coaches[<?=$i?>][note]">
<?php
}
Then in PHP you just iterate over $_POST['coaches'] and then use the properties for each coach how you wish:
if (isset($_POST['coaches'])) {
foreach ($_POST['coaches'] as $coach) {
$name = $coach['name'];
$salary = $coach['salary'];
$note = $coach['note'];
// Now execute the query:
// INSERT INTO coached_tracked (name, salary, note)
// VALUES ($name, $salary, $note);
}
}
Note: remember to sanitize any user-supplied data by using prepared statements with bound parameters to make sure you're not open to SQL injection attacks.
Making a blogging system using L5 and my current set up is all ready except for the saving of the blog posts.
I have 2 buttons. One creates a textarea input and the other creates a file upload interface.
Essentially, after creating a blog post I am left with the structure like so:
<form>
<textarea name="text-update">foo</textarea>
<textarea name="text-update">foo</textarea>
<textarea name="text-update">foo</textarea>
<textarea name="text-update">foo</textarea>
<input type="hidden" value="an image url"/>
<input type="hidden" value="an image url"/>
<textarea name="text-update">foo</textarea>
</form>
Ideally I want to be able to go:
public function store()
{
foreach (INPUTS AS INPUT) {
add new row to database with the content and also the type of input.
}
}
The aim is that instead of having a single blog I instead have blog sections which will belong to a blog post.
If this isn't possible then Ill just have to increment the names of the inputs and figure something out.
Edit: When you add an element to the DOM you can define the array key with an id to preserve the array order.
You can make the inputs an array by adding [] at the end of the name:
<form>
<textarea name="text-update[1]">foo</textarea>
<textarea name="text-update[2]">foo</textarea>
<textarea name="text-update[3]">foo</textarea>
<textarea name="text-update[4]">foo</textarea>
<input type="hidden" name="image[1]" value="an image url"/>
<input type="hidden" name="image[2]" value="an image url"/>
<textarea name="text-update[5]">foo</textarea>
</form>
This will put all the values in an array that you can iterate over
foreach (Request::get('text-update') as $update) {
//add new row to database with the content and also the type of input.
}
foreach (Request::get('image') as $update) {
//add new row to database with the content and also the type of input.
}
Set your fields up like this:
<textarea name="text-update[]">foo</textarea>
using the brackets will take all the text fields and group them into an array that you can then iterate through. You will also need to do the same with hidden fields. Make sure you use the [] in the name like so:
<input type="hidden" name="somename[]" value="an image url"/>
I have three inputs type text in an HTML page and a button which if clicked duplicate each text box (Javascript) making them 6.
<input type="text" name="category[]">
<input type="text" name="quantity[]">
<input type="text" name="amount[]">
<button>Add more</button>
Which generate same inputs again:
<input type="text" name="category[]">
<input type="text" name="quantity[]">
<input type="text" name="amount[]">
A piece of code in Cakephp I have been trying:
$data = $this->request->data;
foreach($data['category'] as $index => $value){
$this->ModelName->save($value);
}
Trying to get two rows inserted at once with quantity, category and amount as columns. But it is not inserting and not giving any error.
Is there a way I can achieve this?
Thanks.
I'm not sure how your model works in cakephp, but you should be able to get a complete grouping of data like:
foreach($data['category'] as $index => $value){
$category = $value
$quantity = $data['quantity'][$index];
$amount = $data['amount'][$index];
// use the above 3 variables however you need to to persist the model
//$this->ModelName->save($value);
}
On a side note, you may want to consider reordering your html inputs to be like:
<input type="text" name="item[0][category]">
<input type="text" name="item[0][quantity]">
<input type="text" name="item[0][amount]">
And then maintain the next index, incrementing the numeric index of item for each additional group
This will allow you to iterate like:
foreach($data['item'] as $index => $group){
//$group['category'];
//$group['quantity'];
//$group['amount'];
}
I have an "Update Profile" script that retrieves the details of the logged in user in a form input, so they can see what the current values are. Like this:
<input type="text" name="first_name" id="first_name" value='<?= $row->f_name; ?>' title="enter your first name.">
This works. When users navigate to the page they see their first name appear in that input box. When they go to change their name and enter in a new value the form submits but keeps the original value and not the updated one. I assume that is because I am hard-coding a value to it with the value attribute.
How can I show the user the value in the input so that if they choose to not edit it, it does submit with the original value and not a blank, but if they do choose to add text to the input box the new string is submitted?
If I understand you correctly:
value="<?=set_value('first_name', $first_name)?>"
The first parameter is the posted value, the second parameter is the default overridden value.
You may want to use placeholder attributes.
<input type="text" name="first_name" placeholder="<?= $row->f_name; ?>">
`if($_GET['first_name']==''){
$first_name= $row->f_name;
}else{
$first_name= $_GET['first_name'];
}`
SQL Query :
"UPDATEyour_table_nameSETfirst_name= '$first_name' WHEREblablabla= '$blablalba';"
<input type="text" name="first_name" id="first_name" value='f_name; ?>' title="enter your first name.">
I have a variable number of fields in a form.
The number of text fields are defined by the user with a function in jquery, but the final code of the form (example) is this:
<form id='form_educ' name='form_educ' method='post' action='form/educ.php'>
<div id='educ'>
<input type='text' name='date1' id='date1'/>
<input type='text' name='date2' id='date2'/>
<input type='text' name='date3' id='date3'/>
<input type='text' name='date4' id='date4'/>
....
</div>
<input type='submit' name='form_educ' value='Refresh'/>
</form>
These text fields when added by the user is create a sql INSERT TO (in another file):
$date = clean($_GET['date']);
"INSERT INTO educ (index_of_form, date, email) VALUES('$index', '', '" .mysql_real_escape_string($_SESSION['SESS_EMAIL']). "')";
$date is date1, or date2, or date3 or date4 (example).
Now in the file educ.php I want to update all text fields in the mysql database.
Usually it is a
$example = clean($ _POST ['example']);
I can do an update in the table and is resolved.
But in my case how can I get all the values โโof the text field on the form and set the $_POST var if the number of fields is variable (could be date1, date2, date3, date4)?
I can think of no reason why form field name should be a unknown variable. Unless you're dealing with repeatable fields, in which case you would use an array like dates[], and you'd know what to expect in the process script.
For additional info see for example: http://www.web-design-talk.co.uk/58/adding-unlimited-form-fields-with-jquery-mysql/
Word of warning for future. When you make the field repeatable, allow users also to delete the fields they might have accidentally insertet. Watch out in the process script missing array keys (numerical index from 0โ10 might be missing some values if the user deleted some form fields before submitting). You can reset the array keys with the array_merge function. Missing keys is an issue if you have two arrays you are trying to add into database as syncronized.
Updated to answer the comment.
Sorry, I don't undestand your question. You don't necessarily have to use hidden field. What you need is a database structure to match your forms function: to support one to many relationship. After all you are inserting multiple dates that relate to one person, or some specific event type, or what ever. Lets assume one user wants to add his three favorite dates in the world. Your form's source code looks like:
<input type="text" name='dateLover' id='dateLover'/>
<input type="text" name="dates[]" id="date1" /> //you need a increasing variable for these id numbers (or dont't put the id at all)
<input type="text" name="dates[]" id="date2" />
<input type="text" name="dates[]" id="date3" />
In addition you could have more fields such as <input type="text" name="extra" />. In submitted $_POST array there would be variables and arrays like: $_POST['dateLover'], $_POST['date'][0], $_POST['date'][1], $_POST['date'][2], $_POST['extra']. You'd take the non-repeatable values straight out of the $_POST array but you need a foreach (or some else loop) to handle the dates array.
Your database has to contain two tables (structure simplified):
person: id, dateLover
date: id, dateLover FK to person.dateLover, date
In your process script you have to:
insert a new dateLover to person and use last_insert_id to get his id
use a foreach to insert new dates to table date (with a dateLover's id as FK)
This all is pretty well demonstrated in the link I supplied earlier. For now, it's hard to give an complete example without undestanding the actual problem.
Update 2.
You are serializing the form, not the div's. So your (dynamically generated) could look like this:
<form id="form_educ" name="form_educ" method="post" action="form/educ.php">
<div id="educ">
<div><!--This is for layout only-->
<input type="text" name="dates[]" id="date0" />
<input type="text" name="names[]" id="name0" />
</div>
<div>
<input type="text" name="dates[]" id="date1" />
<input type="text" name="names[]" id="name1" />
</div>
<div>
<input type="text" name="dates[]" id="date2" />
<input type="text" name="names[]" id="name2" />
</div>
</div>
<input type="submit" name="form_educ" value="Refresh" />
</form>โ
And in your process file you take these arrays from $_POST array and insert them into database maybe like this (with properly escaped and checked values of course...):
//dynamic part of the query
$qEnd = '';
$i = -1;
//this is static part of the query
$qBeginning = "INSERT INTO `date` (`id`, `date`, `name`) VALUES ";
foreach ($_POST['dates'] as $key => $date){
$i++;
$qValues[$i] = "(null, '{$date}', '{$_POST[names][$i]}')"; //never do this, always check values...
//value sets are concatenated one after another to the $qEnd
$qEnd .= $qValues . ',';
}
//combine the query parts and remove extra "," from the end
$q = $qBeginning . rtrim($qEnd, ',');
//now the (single) query ($q) is ready to be executed, echo it just for the fun of it
id should be auto increment field, or this kind of stuff doesn't work on the fly.
Again, this all should be clear in the jQuery link example so please read it carefully.
You should know all of the possible columns that could be updated before hand. Just check to see if those are set in the $_POST variable, then if they are append the insert or update statement with those values.
DANGER: Just looping on the $_POST variable looking at all params may end up inserting not database related POST fields into your insert statement and breaking.
Also when using these methods, be aware of SQL Injection, and use parameterized queries and never directly insert POST variable names or values into the SQL Statment.