Group Arrays By Another Array? - php

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);
}

Related

how to use the single input received multiple times in php

for example, I receive two inputs value1 and value2 and I want this input for different functions. Like addition, subtraction and multiplication.
my code
<?php
$x = $_POST['fnum'];
$y = $_POST['snum'];
if (isset($_POST['add'])) {
$sum = $x + $y;
echo "Result:<input type='text' value='$sum'/>";
}
if (isset($_POST['sub'])) {
$sub = $x - $y;
echo "Result:<input type='text' value='$sub'/>";
}
if (isset($_POST['mul'])) {
$mul = $x * $y;
echo "Result:<input type='text' value='$mul'/>";
}
<body>
<form method="post">
Enter first number <input type="text" name="fnum" />
<hr />
Enter second number <input type="text" name="snum" />
<hr />
<input type="submit" name="add" value="ADD" />
<input type="submit" name="sub" value="Subtract" />
<input type="submit" name="mul" value="Multiply" />
</form>
</body>
In this it is asking me to feed input for each operation separately
Good, Just use the posted value in your form input like -
Enter first number <input type="text" name="fnum" value="<?php echo #$_POST['fnum'];?>"/><hr/>
Enter second number <input type="text" name="snum" value="<?php echo #$_POST['snum'];?>"/><hr/>
So that user don't need to put the same value again and when press the other buttons the form will automatically submit with the previous values.
Note: Remember, you need to check all the posted value is set or not and use proper conditions of POST method. Have a look at the given example of your problem as solution, I give it here to give you a proper guide.
Example:
<?php
$x = 0;
$y = 0;
if(isset($_POST['submit'])) {
$x = $_POST['fnum'];
$y = $_POST['snum'];
$operator = "";
if($_POST['submit'] == 'ADD') {
$operator = "+";
} elseif($_POST['submit'] == 'Subtract') {
$operator = "-";
} elseif($_POST['submit'] == 'Multiply') {
$operator = "*";
}
$result = $x . $operator . $y;
}?>
Your form will be-
<form method="post">
Enter first number <input type="text" name="fnum" value="<?php echo $x;?>"/><hr/>
Enter second number <input type="text" name="snum" value="<?php echo $y;?>"/><hr/>
<input type="submit" name="submit" value="ADD"/>
<input type="submit" name="submit" value="Subtract"/>
<input type="submit" name="submit" value="Multiply"/>
</form>
Result:
<input type='text' value='<?php echo (isset($result) ? $result : "-";)?>'/>

array blowing my mind

$va_fields = array();
$c = 0;
$field_num = 'field-'.$c;
settype($c,"integer");
while (isset($_POST[$field_num])){
$posted_field = $_POST[$field_num];
$va_fields = array( $c => $posted_field);
echo $c.': ';
echo '$posted_field: '.$posted_field;
$c+=1;
$field_num = 'field-'.$c;
echo ' <br /> va_fields - c:'.$va_fields[$c];
echo ' <br /> ';
}
For some reason, I cannot for the life of me get the variable $posted_fields into an array.
The values of $posted_field are what I need them to be, so I'm getting the data from the post. Then I try to store them in an array, and check the array and they aren't there. What am I doing wrong?
Edit: here's my form:
<form method="post" action="<?php echo get_site_url(); ?>/wp-admin/admin-post.php">
<input type="hidden" name="action" value="cpt_field_opts" />
<!-- some inputs here ... -->
<?php wp_nonce_field( 'cpt_field_opts', '_wp_nonce' ); ?>
<input type="hidden" name="post_type" value="<?php echo $post_type; ?>">
<input type="hidden" name="origin" value="<?php echo "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>" />
<?php
$c = 0;
foreach ($fields as $field){
?>
<input type="textarea" id="field-<?php echo $c; ?>" name="field-<?php echo $c; ?>" value="<?php echo $field; ?>" size="25" /></br>
<?php
$c += 1;
}
?>
<input type="submit" value="Submit" >
</form>
<form method="post" action="<?php echo get_site_url(); ?>/wp-admin/admin-post.php">
<?php wp_nonce_field( 'cpt_field_opts_new', '_wp_nonce_2' ); ?>
<input type="hidden" name="post_type" value="<?php echo $post_type; ?>" />
<input type="hidden" name="action" value="cpt_field_opts_new" />
<input type="hidden" name="origin" value="<?php echo "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>" />
<input type="submit" value="New" />
</form>
Many people are telling me to rewrite the array as this line:
$va_fields[$c] = $posted_field;
Which I have done, but I also started out with that and it still wasn't working
If you have a bunch of values in $_POST with names like "field-0", "field-1", etc, and you're trying to get them into an array:
$c = 0;
while (isset($_POST["field-$c"])){
// This creates a new element in $va_fields with key=$c and value=$_POST["field-$c"]
$va_fields[$c] = $_POST["field-$c"];
}
var_dump($va_fields); // should show you the array you want
But really, it would be easier to just modify your form to use inputs with name=field[] instead of numbering them. Then you would already have the array in $_POST['fields'] without having to do anything.
It is simple just iterate the $_POST array
<?php
$va_fields = array();
$c=0;
foreach($_POST as $val){
echo '$posted_field: '. $val;
$va_fields[$c] = $val;
}
var_dump($va_fields);
?>

Displaying mysql data through hidden field values

I am trying to display mysql records through hidden field values, but nothing displays.
A little help!
Here's the code;
Html:
<form name="form11" method="post" action="hpdata.php" enctype="multipart/form-data">
<input name="pro" id="pro" type="hidden" value= "CMS" />
<input name="piror" id="piror" type="hidden" value= "P1" />
<input name="stat" id="stat" type="hidden" value= "In Progress" />
<input type="submit" name="submit" id="submit" class="groovybutton" value="...">
</form>
PHP:
<?php
$project = $_POST["pro"];
$pirority = $_POST["piror"];
$status = $_POST["stat"];
mysql_connect ("one", "two", "three");
mysql_select_db ("wsms");
$rest = mysql_query("SELECT * FROM sheet WHERE project='$project' AND
pirority='$pirority' AND status='$status'");
while($row = mysql_fetch_array($rest))
{
echo $row['id'] . " " . $row['date']; echo "<br>";
}
?>
Put isset into your php code
Example
<?php
if(isset($_POST['submit'])){
echo $project = $_POST["pro"]."<br>";
echo $pirority = $_POST["piror"]."<br>";
echo $status = $_POST["stat"];
/* mysql_connect ("one", "two", "three");
mysql_select_db ("wsms");
$rest = mysql_query("SELECT * FROM sheet WHERE project='$project' AND
pirority='$pirority' AND status='$status'");
while($row = mysql_fetch_array($rest))
{
echo $row['id'] . " " . $row['date']; echo "<br>";
}*/
}
?>
<form name="form11" method="post" action="" enctype="multipart/form-data">
<input name="pro" id="pro" type="hidden" value= "CMS" />
<input name="piror" id="piror" type="hidden" value= "P1" />
<input name="stat" id="stat" type="hidden" value= "In Progress" />
<input type="submit" name="submit" id="submit" class="groovybutton" value="...">
</form>
Output
CMS
P1
In Progress
First of all check that if the data is coming in the post or not:
<?php
echo "<pre>";
print_r($_POST);
exit;
?>
If yes than remove the print code i provided , and use extract($_POST); at the top of your PHP code. You query will become like this:
$rest = mysql_query("SELECT * FROM sheet WHERE project='$pro' AND
pirority='$piror' AND status='$stat'");

php: how to shorten many $_POST[];

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]
}

Post variables not being sent

This is really bugging me and I can't figure it out. I have a form with a few options being sent by POST:
<form method="POST" action="scripts/submit.php"><strong>
To User: <input type="text" name="ID" size="21" /><br />
Short Description: <input type="text" name="Item" size="21" /><br />
Link: <input type="text" name="Link" size="21" /><br />
Points: <select name="Points">
<option value="1" selected="selected">1</option>
<option value="0">0</option><option value="-1">-1</option>
</select> (1 = Positive, 0 = Neutral, -1 = Negative)<br />
Text: <br /><textarea name="Text" rows="5" cols="50"/></textarea></strong><br />
<input type="submit" value="Send" />
</form>
And here is the portion of submit.php that is giving me trouble:
<?php
include('functions.php');
Connect();
if(!isset($_SESSION))
{
session_start();
}
$id_from = $_SESSION['SESS_MEMBER_ID'];
$id_to = Sanitize($_POST['ID']);
$item = Sanitize($_POST['Item']);
$link = Sanitize($_POST['Link']);
$points= Sanitize($_POST['points']);
$text = Sanitize($_POST['Text']);
Does anyone see an issue here? I am getting undefined index's from all of the variables except the session one.
Thanks in advance.
edit: If i just have this:
<?php
include('functions.php');
Connect();
if(!isset($_SESSION))
{
session_start();
}
$id_from = $_SESSION['SESS_MEMBER_ID'];
$id_to = Sanitize($_POST['ID']);
$item = Sanitize($_POST['Item']);
$link = Sanitize($_POST['Link']);
$points = Sanitize($_POST['points']);
$text = Sanitize($_POST['Text']);
?>
The variables populate just fine. If I add:
$id_query=mysql_query("SELECT ID FROM tbl_users WHERE Username = '$id_to'");
$count=mysql_num_rows($id_query);
$id_row=mysql_fetch_array($id_query);
$id_to=$id_row['ID'];
if ($points> 1 || $points< -1) {
echo "Nice try";
exit();
} else {
if(!($id_to == $id_from))
{
if($count==1)
{
mysql_query("INSERT INTO tbl_data (Item, Link, Points, Text, ID_To, ID_From) VALUES ('$item', '$link', '$points', '$text', '$id_to','$id_from')");
header('Location:?id=submit');
}
else
{
echo "Nice try1";
}
}
else
{
echo "Nice try2";
}
}
I just took your code over at my dev server at tried to test run it. Since I don't know what your Sanitize() do, I can't be sure what is going on inside this function.
If you try to remove the Sanitize(), I'm pretty sure it would work and you will have to look inside this to find the bug.
I'm guessing you might be missing something like ($var, str) for sanitize a string. Can you please tell a little more about this function ?
edit: some minor spelling errors.
Edit: Did some more test and made the error happen and the two codes shows it. The 1st works, while the 2nd gives me a empty var_dump.
This one gives me a full var_dump();
<?
function Sanitize($String) {
$output = mysql_real_escape_string(stripslashes($String));
return $output;
}
if(!isset($_SESSION))
{
session_start();
}
?>
<form method="post" action=""><strong>
To User: <input type="text" name="ID" size="21" /><br />
Short Description: <input type="text" name="Item" size="21" /><br />
Link: <input type="text" name="Link" size="21" /><br />
Points: <select name="Points"><option value="1" selected="selected">1</option><option value="0">0</option><option value="-1">-1</option></select> (1 = Positive, 0 = Neutral, -1 = Negative)<br />
Text: <br /><textarea name="Text" rows="5" cols="50"/></textarea></strong><br />
<input type="submit" value="Send" />
</form>
<?
$id_from = $_SESSION['SESS_MEMBER_ID'];
$id_to = Sanitize($_POST['ID']);
$item = Sanitize($_POST['Item']);
$link = Sanitize($_POST['Link']);
$points= Sanitize($_POST['points']);
$text = Sanitize($_POST['Text']);
var_dump($_POST);
echo $text;
?>
This one gives me an empty var_dump
<?
if(!isset($_SESSION))
{
session_start();
}
?>
<form method="post" action=""><strong>
To User: <input type="text" name="ID" size="21" /><br />
Short Description: <input type="text" name="Item" size="21" /><br />
Link: <input type="text" name="Link" size="21" /><br />
Points: <select name="Points"><option value="1" selected="selected">1</option><option value="0">0</option><option value="-1">-1</option></select> (1 = Positive, 0 = Neutral, -1 = Negative)<br />
Text: <br /><textarea name="Text" rows="5" cols="50"/></textarea></strong><br />
<input type="submit" value="Send" />
</form>
<?
$id_from = $_SESSION['SESS_MEMBER_ID'];
$id_to = Sanitize($_POST['ID']);
$item = Sanitize($_POST['Item']);
$link = Sanitize($_POST['Link']);
$points= Sanitize($_POST['points']);
$text = Sanitize($_POST['Text']);
var_dump($_POST);
echo $text;
?>
based on your comment that you have this code:
$id_query = mysql_query("SELECT ID FROM tbl_users WHERE Username = '$id_to'");
$count = mysql_num_rows($id_query);
$id_row = mysql_fetch_array($id_query);
$id_to = $id_row['ID'];
if ($points > 1 || $points < -1) {
} else {
if (! ($id_to == $id_from)) {
if ($count == 1) {
mysql_query("INSERT INTO tbl_data (Item, Link) VALUES ('$item', '$link')");
header('Location:?id=submit');
} else {}
} else {}
}
I think the problem is on the line that says:
header('Location:?id=submit');
Perhaps you're testing with something that somehow make $points either greater than 1 or less than -1, $count is 1, and $id_to is different from $id_from, which then make the else block executed and (especially the line) header() executed, and user get redirect immediately.
To check if this is true, try var_dump($_GET) to see if you got something like:
array (size=1)
'id' => string 'submit' (length=6)
If you do, and perhaps the database isn't updated, then it's the mysql_query that sits right before the header is the one that you need to check.
Hope this helps.

Categories