I'm working on a page with many insert fields.
how can i shorten the following code?
$title_1 = $_POST['title_1'];
$content_1 = $_POST['content_1'];
$link_1 = $_POST['link_1'];
$img_link_1 = $_POST['img_link_1'];
$title_2 = $_POST['title_2'];
$content_2 = $_POST['content_2'];
$link_2 = $_POST['link_2'];
$img_link_2 = $_POST['img_link_2'];
$title_3 = $_POST['title_3'];
$content_3 = $_POST['content_3'];
$link_3 = $_POST['link_3'];
$img_link_3 = $_POST['img_link_3'];
You could loop through the $_POST array like this:
foreach ($_POST as $key => $value) {
${$key} = $value;
}
This will make your post variable like $_POST['title_1'] into $title_1
Remember your post names will have to be the exact names you want your variables to be referenced by.
I would do:
$howmany = 3; // How many sets of fields are submitted.
for($i=0;$i<$howmany;$i++){
$field[$i]['title'] = $_POST['title_'.$i];
$field[$i]['content'] = $_POST['content_'.$i];
$field[$i]['link'] = $_POST['link_'.$i];
$field[$i]['img_link'] = $_POST['img_link_'.$i];
}
Then you can access data in $field[1]['title'] form.
You can use extract (http://php.net/manual/en/function.extract.php): extract($_POST)
But you should be careful -- what if the client POSTs user_id, or something? At the least, you should specify that $_POST values won't overwrite already-defined variables: extract($_POST, EXTR_SKIP)
I redid this answer after you edited your post. Use variable variables.
foreach ($_POST as $key => $val)
{
if (preg_match('/^(([a-z]+_)+\d)$/', $key, $match)
{
$$match[0] = $val;
}
}
Use [a-z0-9] or [a-zA-Z0-9] as alternatives.
<?php
$key_prefixes = array (
'title',
'content',
'link',
'img_link'
);
$i = 1;
while (true) {
$post_values_missing = 0;
foreach ($key_prefixes as $key_prefix) {
$key = $key_prefix . '_' . $i;
if (!isset($_POST[$key])) {
$post_values_missing += 1;
continue;
};
$val = $_POST[$key];
// do something with $val
}
// did you get any values through this iteration?
$post_values_exist_bool = (count($key_prefixes) !== $post_values_missing);
// if not, you must've gotten them all
if (false === $post_values_exist_bool) {
break;
}
$i += 1;
}
The cleanest way to do this would be to use PHP's POST data processing capabilities to do the work for you.
Consider using your HTML form names as follows:
<form action="{url}" method="post">
<input type="text" name="data[0][title]" />
<input type="text" name="data[0][content]" />
<input type="text" name="data[0][link]" />
<input type="text" name="data[0][image_link]" />
<input type="text" name="data[1][title]" />
<input type="text" name="data[1][content]" />
<input type="text" name="data[1][link]" />
<input type="text" name="data[1][image_link]" />
...
</form>
In PHP extract the data as follows:
$data = $_POST['data'];
This shortens your PHP code to just one line. This statement will directly give you an array in PHP of the data form input. A var_dump will look as follows:
array (
0 => array('title'=>'...','content'=>'...','link'=>'...','image_link'=>'...'),
1 => array('title'=>'...','content'=>'...','link'=>'...','image_link'=>'...'),
...
)
You don't have to change your name, just make it array;
<input type="text" name="title[]" />
<input type="text" name="content[]" />
<input type="text" name="link[]" />
<input type="text" name="image_link[]" />
<input type="text" name="title[]" />
<input type="text" name="content[]" />
<input type="text" name="link[]" />
<input type="text" name="image_link[]" />
<input type="text" name="title[]" />
<input type="text" name="content[]" />
<input type="text" name="link[]" />
<input type="text" name="image_link[]" />
PHP:
extract($_POST);
$count=count($title);
for($i=0;$i<$count;$i++) {
//You can perform your any function on this loop, to get title use $title[$i]
}
Related
I want to post more than one variable using foreach loop into my database, i was able to post one variable using this code
foreach ($_POST['part'] as $key=>$value) {
if($value!='')
$part = $value;
Now i want to post more than one am not getting it, am trying this
foreach ($_POST['part'] && ($_unique_id) as $key=>$value)) {
if($value!='')
$part = $value;
$unique_id = $value;
Any help will be appreciated.
If you have the following form:
<form method="post">
<input type="text" name="first_name" />
<input type="text" name="last_name" />
</form>
You can read the post in PHP with the following:
$firstName = $_POST['first_name'];
$lastName = $_POST['last_name'];
Hope this gives you an idea how it works, not completely sure why you would need a foreach.
Perhaps you would prefer to have your name attributes as arrays as in :
<form method="post" action="">
<input type="text" name="part[firstname]" />
<input type="text" name="part[last_name]" />
<input type="submit" name="button" value="submit" />
</form>
Then in php
foreach($_POST['part'] as $key => $value){
//do your stuff
}
$i=0;
foreach ($_POST['part'] as $key=>$value)) {
if($value!='' && $_unique_id[$i]!='')
$part = $value;
$unique_id = $_unique_id[$i];
$i++;
}
Use this way its work.
Try this
foreach (array_combine($part, $unique_id) as $part_value => $unique_id_value)
I'm trying to sort one array by another array. Both these arrays get their content from a form.
Here's my form code:
<form method="post" action="">
<div class="groupcontainer">
<br/><label>Group One:</label><br/>
<input type="text" name="groupname[]" value="groupone" /><br/>
<br/><label>Variable Group One:</label><br/>
<input type="text" name="variable[]" value="variableone" />
<input type="text" name="variable[]" value="variabletwo" />
</div>
<br/>
<div class="groupcontainer">
<br/><label>Group Two:</label><br/>
<input type="text" name="groupname[]" value="grouptwo" /><br/>
<br/><label>Variable Group Two:</label><br/>
<input type="text" name="variable[]" value="variablethree" />
<input type="text" name="variable[]" value="variablefour" />
</div>
<br/>
<input type="submit" name="submit" value="Submit" />
</form>
Here's the PHP code:
<?php
if (!$_POST['submit'] == "") {
foreach($_POST['groupname'] as $groupname) {
$groupnum = 1;
foreach($_POST['variable'] as $variable) {
print "$".$groupname.$groupnum." = '".$variable."';<br/>";
$groupnum++;
}
print "$".$groupname." = array(";
for ($arrnum = 1; $arrnum <= count($_POST['variable']); $arrnum++) {
print "$".$groupname.$arrnum.", ";
}
print ");<br/><br/>";
}
}
?>
This is the result I get when I submit the form:
$groupone1 = '$variableone';
$groupone2 = '$variabletwo';
$groupone3 = '$variablethree';
$groupone4 = '$variablefour';
$groupone = array($groupone1, $groupone2, $groupone3, $groupone4, )
$grouptwo1 = '$variableone';
$grouptwo2 = '$variabletwo';
$grouptwo3 = '$variablethree';
$grouptwo4 = '$variablefour';
$grouptwo = array($grouptwo1, $grouptwo2, $grouptwo3, $grouptwo4, )
This is the result that I actually want:
$groupone1 = '$variableone';
$groupone2 = '$variabletwo';
$groupone = array($groupone1, $groupone2)
$grouptwo1 = '$variablethree';
$grouptwo2 = '$variablefour';
$grouptwo = array($grouptwo1, $grouptwo2)
The whole thing needs to be dynamic since I want to add as many groups and variables as I want.
I've been searching for an answer for days and already asked two people who didn't know an answer. Maybe you guys can help. Thanks!
Update:
Just to clarify a few points:
So basically I want to be able to add as many input forms as I want (I use jQuery for that) to create as many groups and variables as I want, for example like this:
$groupwuteva1 = 'hello';
$groupwuteva2 = 'bye':
$randomname1 = 'green';
$randomname2 = 'blue';
$randomname3 = 'red';
$blabla1 = 'abc';
$blabla2 = 'xyz';
$blabla3 = '123';
$blabla4 = 'bla';
Whatever I use as groupname will be used in array one, e.g. I call a group "Colors" and the variables I put into the form for that group are "blue", "red" and "green". Then I would get this code:
$colors1 = 'green';
$colors2 = 'blue';
$colors3 = 'red';
I hope this clairfies some questions. And thanks a ton for all responses so far!
You can take the group name as a container to store all associated variable values in it. And later, use variable variables and implode() function to process your html form.
HTML
<form method="post" action="">
<div class="groupcontainer">
<br/><label>Groupe One:</label><br/>
<input type="text" name="groupname[]" value="groupone" /><br/>
<br/><label>Variable Group One:</label><br/>
<input type="text" name="groupone[]" value="variableone" />
<input type="text" name="groupone[]" value="variabletwo" />
</div>
<br/>
<div class="groupcontainer">
<br/><label>Groupe Two:</label><br/>
<input type="text" name="groupname[]" value="grouptwo" /><br/>
<br/><label>Variable Group One:</label><br/>
<input type="text" name="grouptwo[]" value="variablethree" />
<input type="text" name="grouptwo[]" value="variablefour" />
</div>
<br/>
<input type="submit" name="submit" value="Submit" />
</form>
PHP
if(isset($_POST['submit'])){
foreach($_POST['groupname'] as $value){
$arr = array();
$i = 1;
foreach($_POST[$value] as $v){
$var = $value . $i;
$$var = $v;
echo $var . " = " . $$var . "<br />";
$arr[] = $$var;
++$i;
}
$output = $value . " = array(" . implode(",", $arr) . ")";
echo $output . "<br /><br />";
}
}
Output:
groupone1 = variableone
groupone2 = variabletwo
groupone = array(variableone,variabletwo)
grouptwo1 = variablethree
grouptwo2 = variablefour
grouptwo = array(variablethree,variablefour)
try this form:
<form method="post" action="">
<?php foreach(array('groupone', 'grouptwo') as $num):?>
<div class="groupcontainer">
<br/><label>Groupe <?php echo $num;?>:</label><br/>
<input type="text" name="groupname[]" value="<?php echo $num;?>" /><br/>
<br/><label>Variable Group <?php echo $num;?>:</label><br/>
<input type="text" name="variable[<?php echo $num;?>][]" value="<?php echo uniqid();?>" />
<input type="text" name="variable[<?php echo $num;?>][]" value="<?php echo uniqid();?>" />
</div>
<br/>
<?php endforeach;?>
<input type="submit" name="submit" value="Submit" />
</form>
and code:
if ($_POST) {
foreach($_POST['groupname'] as $groupname) {
$$groupname = array();
foreach($_POST['variable'][$groupname] as $variable) {
${$groupname}[] = $variable;
}
}
var_dump($groupone);
var_dump($grouptwo);
}
There are two values I want to get from user that is name and price. I have made an auto generating rows function that generate input boxes with same name. Now the thing is I want to store them in database. I using foreach but that only get one array. I want to store both name as well as price. How can I do that. Here is my code.
HTML Form
<form method="post">
<input type="text" name="name[]" /><input type="text" name="price[]" />
<input type="text" name="name[]" /><input type="text" name="price[]" />
<input type="text" name="name[]" /><input type="text" name="price[]" />
<input type="text" name="name[]" /><input type="text" name="price[]" />
<input type="submit" value="Submit" name="submit" />
</form>
PHP Code
if(isset($_POST['submit']))
{
foreach($_POST['name'] as $name)
{
echo $name;
}
}
Call the index in the loop as well and then select the corresponding value from the other array.
foreach($_POST['name'] as $id => $name)
{
echo $name;
echo $_POST['price'][$id]
}
How about this
if(isset($_POST['submit']))
{
$names = $_POST['name']; # array
$prices = $_POST['price']; # array
foreach($names as $id => $name)
{
echo $name;
echo "<br>";
echo $prices[$id]
}
}
Provided you know both arrays will be the same length, a simple for loop will do:
if(isset($_POST['submit']) && count($_POST['name']) == count($_POST['price']))
{
for($i=0; $i < count($_POST['name']); $i++)
{
echo $_POST['name'][$i] . ' ' . $_POST['price'][$i];
}
}
Try this
$names = array_combine($_POST['name'], $_POST['price']);
foreach($names as $firstname => $price) {
echo $firstname . ' ' . $price . '<br>';
}
I want to send the "fill[]" and the "item[]" and my problem is the function write cant get the values of the variables, why?
What is wrong? Im new in this stuff.
<form action="/fill_sites/fill.php" method="get">
<input type="text" size="24" maxlength="20" name="fill[0]"/>
<input type="hidden" name="item[0]value="hella_apfelschorle"/>
<input type="text" size="24" maxlength="20" name="fill[1]"/>
<input type="hidden" name="item[1]" value="volvic_wasser"/>
..... so on
<input type="submit" value="Abschicken"/>
------------------------------------------------------------>[fill/php]>
$fill[0] = $_GET["fill[0]"];
$fill[1] = $_GET["fill[1]"];
$fill[2] = $_GET["fill[2]"];
$fill[3] = $_GET["fill[3]"];
$fill[4] = $_GET["fill[4]"];
$fill[5] = $_GET["fill[5]"];
$fill[6] = $_GET["fill[6]"];
$fill[7] = $_GET["fill[7]"];
$fill[8] = $_GET["fill[8]"];
$fill[9] = $_GET["fill[9]"];
$item[0] = $_GET["item[0]"];
$item[1] = $_GET["item[1]"];
$item[2] = $_GET["item[2]"];
$item[3] = $_GET["item[3]"];
$item[4] = $_GET["item[4]"];
$item[5] = $_GET["item[5]"];
$item[6] = $_GET["item[6]"];
$item[7] = $_GET["item[7]"];
$item[8] = $_GET["item[8]"];
$item[9] = $_GET["item[9]"];
write($counterFilename[$item[]], $fill);
you can do this by following code. it will get complete array.
$item = $_Get['item'];
$fill= $_Get['fill'];
use php's foreach statement to retrieve the content of fill and item
$fills = $_GET['fill'];
foreach($fills as $fill)
{
//do something with $fill
}
and the same for $item
I have an error that I can't figure out...
Om my webpage there is a form that the user has the ability to add some new input fields to. If the user is submitting the form, then the optional fields is empty when the php-file is handing them, why?
HTML:
<form method="post" action="newRequest.php">
<input type="text" name="title" />
<input type="hidden" name="fname" value="0" />
<input type="checkbox" name="fname" value="1"/>
<input type="hidden" name="ename" value="0" />
<input type="checkbox" name="ename" value="1" />
<input type="hidden" name="seat" value="0" />
<input type="checkbox" name="seat" value="1" />
<input type="hidden" name="fields" value="0" />
<input type="text" id="fields" name="fields" />
<input type="submit" />
</form>
PHP:
if (strlen($_POST[title]) > 2) {
$toDb[title] = $_POST[title];
} else {
error('title');
}
$toDb[fname] = $_POST[fname];
$toDb[ename] = $_POST[ename];
$toDb[seat] = $_POST[seat];
if ($_POST[fields] > 0) {
$i = 0;
while ($i < $_POST[fields]) {
$toDb[optional][$i] = $_POST[optional-$i];
$i++;
}
$toDb[optional] = serialize($toDb[optional]);
} else {
$toDb[optional] = 0;
}
newEvent($toDb,$dbh);
JQuery that is adding dynamical fields:
$(document).ready(function() {
$('#fields').focusout(function(){
var fields = $('#fields').val();
var i = 0;
while(i < fields) {
$('#fields').after("Valfritt fält "+(i+1)+":<input type='text' name='optional"+i+"' />");
i++;
}
})
})
You should quote array indexes. It should be
$toDb['optional'][$i] = $_POST['optional'.$i];
You are missing commas in $_POST
$toDb['fname'] = $_POST['fname'];
$toDb['ename'] = $_POST['ename'];
$toDb['seat'] = $_POST['seat'];
Here is your modified code
if (strlen($_POST['title']) > 2) {
$toDb['title'] = $_POST['title'];
} else {
error('title');
}
$toDb['fname'] = $_POST['fname'];
$toDb['ename'] = $_POST['ename'];
$toDb['seat'] = $_POST['seat'];
if (count($_POST) > 0) {
$i = 0;
while ($i < count($_POST)) {
$toDb['optional'][$i] = $_POST['optional-'.$i];
$i++;
}
$toDb['optional'] = serialize($toDb['optional']);
} else {
$toDb['optional'] = 0;
}
newEvent($toDb,$dbh);
Also use count() to check if $_POST has values > 0.
I faced the same problem and I solved it using Javascript, like this :
add a new text field every time a button is pressed