How to combine a PHP variable and $_REQUEST? - php

I am retrieving data from a dynamic form. For that I have counted the number of elements on the form and made each input have a unique name, using the counter variable, eg:
echo "<input type='hidden' name='itemid" . $i . "' value='" . $row['itemid'] . "' />";
On the relieving page I need to modify $_REQUEST[] to include its own counter variable, eg:
while($x <= $counter){
$itemid = trim($_REQUEST['itemid" . $x . "']);
$x = $x + 1;
};
Does anyone know the correct way of combining the $_REQUEST and $x variable?

$itemid = trim($_REQUEST['itemid" . $x . "']);
should be
$itemid = trim($_REQUEST['itemid' . $x]);
A better way to do this would be to use arrays. Then you don't need to use a counter to keep track of where you are:
echo "<input type='hidden' name='itemid[]' value='" . $row['itemid'] . "' />";
PHP:
foreach ($_REQUEST['itemid'] as $item) {
// do stuff
}

Related

Creating HTML table with POST

I am trying to create a webpage that takes user input, posts it to a creation page and then creates another webpage displaying the data in a html table. I am using file_put_contents to create the webpage and I am getting an error whenever I try to include a loop to get the content from 3 td's to be output. Here is what I have so far. I will mention I posted earlier, however I deleted that as that post was confusing, lacked detail and examples.
This is the input field for user (deleteBox does not get posted)
The user will input: An ingredient, the amount and a note (txt is an empty variable)
<tr><td><input type='checkbox' name='deleteBox'></td><td>" + "<input type='text' name='ingredient[]' value='" + txt + "'/>" + "</td><td>" + "<input type='text' name='amount[]' value='" + txt + "'/>" + "</td> + <td>" + "<input type='text' name='note[]' value='" + txt + "'/>" + "</td></tr>
I've tried the below with both the for loop in a variable and directly entering it into the $strOut. I don't really know if this is how you're supposed to do it (clearly not, as it doesn't work -> gives error unexpected 'for' on line 42 [$tbl line]) and cannot find a work around. How would I make the array data display in the output for file_put_content so that it doesn't create errors?
$ingredient = $_POST['ingredient'];
$amount = $_POST['amount'];
$note = $_POST['note'];
$tbl = for ($i = 0; $i < count($ingredient); $i++) {
echo '<tr>';
echo '<td>' . $ingredient[$i] . '</td>';
echo '<td>' . $amount[$i] . '</td>';
echo '<td>' . $note[$i] . '</td>';
echo '</tr>';
}
$strOut = '<!DOCTYPE html>'
. '<table class="recipe-ingredients">'
. '<tr>'
. '<th class="table-th-large">Ingredient</th>'
. '<th class="table-th-medium">Amount</th>'
. '<th class="table-th-xl">Note</th>'
// User input tr goes here
. $tbl
. '</table>';
// Closing html tags after
file_put_contents("example.php", $strOut);
Any suggestions or work arounds would be much appreciated.
$tbl = '';
for ($i = 0; $i < count($ingredient); $i++) {
$tbl.= '<tr>';
$tbl.= '<td>' . $ingredient[$i] . '</td>';
$tbl.= '<td>' . $amount[$i] . '</td>';
$tbl.= '<td>' . $note[$i] . '</td>';
$tbl.= '</tr>';
}
Use this.
By the way, You forgot to put a closing </tr> in the heading row.

Capture the answers from form within while loop

I want to capture answers from forms within a big loop and then update the results into database. I am not sure how to do that, I have made a sample code as follows, and want to for each Save button save each question results. Say we have 5 questions, when I click save botton 1, save answers for question 1; when click save button , save answers for question 2..
Thanks very very much, this drove me crazy.....
<?php
$x=1;
$output="";
while($x<=5){
$output .= "<form action='index.php' id='" . $x . "' method='POST'>";
$output .="<h2>Question" . $x . "</h2>";
$output .= "<h3>selection</h3>";
$output .= "<ul><li><input type='radio' name='selection" . $x . "' value='1'>1</li>";
$output .= "<li><input type='radio' name='selection" . $x . "' value='2'>2</li>";
$output .= "<li><input type='radio' name='selection" . $x . "' value='3'>3</li></ul>";
$output .= "<h3>choice</h3>";
$output .= "<ul><li><input type='radio' name='choice" . $x . "' value='a'>a</li>";
$output .= "<li><input type='radio' name='choice" . $x . "' value='b'>b</li></ul>";
$output .= "<p><textarea rows='4' cols='50' name='commentory" . $x . "' form='usrform' placeholder='Enter text here...'></textarea></p>";
$output .= "<input type='submit' name='saveResult" . $x . "' value='Save'>";
$output .= "</form>";
$output .="<br>";
$x++;
}
echo $output;
if(isset($_POST['saveResult' .$x])){
$selection = $_POST['selection' . $x];
$choice = $_POST['choice' . $x];
$commentory = $_POST['commentory' . $x];
$result=$selection . $choice . $commentory;
echo "<script>alert($result])</script>";
// This part just a sample part as I dont know how to capture the results
}
?>
In your current file, you could change the first line in the while loop to this:
$output .= "<form action='index.php?question=" . $x . "' id='" . $x . "' method='POST'>";
What this does is sends a GET request with a number, from 1-5, based on what question was submitted. You can then do something like this to differentiate between your five (or however many) questions:
$questionNumber = $_GET['question']; // The ?question= parameter sent in the URL
if($questionNumber == 1) {
// Question 1 logic here
} else if($questionNumber == 2) {
// Question 2 logic here
} ...
Or do the same thing using a switch statement:
switch($questionNumber) {
case 1:
// Question 1 logic here
break;
...
}

php add random array not repeating most recent 5

I'm trying to re-write this code so that it goes with the columns that are going to be user-defined. With this, my challenge consists of
a) Needs to select random starting item from array
b) Select the next random color from the original array that is not equivalent to the most recent items selected based the number: $intNotesColumn + 1
I was thinking a do-while statement nested inside another was appropriate for this but am unsure how to go about this. Here is my code so far:
$metroUIcolors = array( "#A30061", "#8200CC", "008987", "#A05000", "#B85A93", "#C07807", "#E51400", "#297A29" );
$metroUIcolorsLength = count($metroUIcolors);
$intNotesColumn = 3; // This will be user-defined later
// Now I query the SQL database to get my base-code
if ($result->num_rows > 0) {
// output data of each row
echo '<table border=0 valign=top>'
. '<tr>'
. '<td colspan=' . $intNotesColumn . '>' . '<h1>header</h1>' . '</td>'
. '</tr>'
. '<tr>';
$counterRank = 1;
while($row = $result->fetch_assoc()) {
echo "<td bgcolor=" . $metroUIcolors[rand(0, $metroUIcolorsLength - 1)]. ">"
. "<h2>" . $row["username"] . '</h2><br />'
. "<p class='notes'>" . $row["notes"] . "</p>"
. "<p class='footnotes'>"
. "<br />Last Reset: " . $row["lastReset"]
. '<br />Last Update: ' . $row['lastUpdate']
. '<br />SessionID: ' . $row["sessionID"]
. "<br />Counter = " . $counterRank . "</td>". '</p>';
if ($counterRank % $intNotesColumn == 0)
{
echo '</tr><tr>';
}
$counterRank++;
}
echo '</tr></table>';
} else{
echo "No Notes Found in databases";
}
Then, why don't you do it order picking one color at a time. You could use shuffle() so that there will be a different starting color everytime.
<?php
$counterRank = 1;
// shuffle the array
shuffle($metroUIcolors);
while($row = $result->fetch_assoc()) {
$rand_color = $counterRank % $metroUIcolorsLength;
echo "<td bgcolor=" . $metroUIcolors[$rand_color]. ">";
// everything else
$counterRank++;
}
?>
If you insist on doing the way you said, you may create an array $colorCount which has color codes as keys and count as values.
<?php
$counterRank = 1;
$colorCount = array_fill_keys($metroUIcolors, 0);
while($row = $result->fetch_assoc()) {
do {
$rand_color = $metroUIcolors[rand(0, $metroUIcolorsLength - 1)];
} while ($colorCount[$rand_color] > 5);
echo "<td bgcolor=" . $rand_color. ">";
// everything else
$counterRank++;
$colorCount[$rand_color] += 1;
}
?>

Mechanism to display JSON array in checkboxes

I used the JSON to create an array multidimensional. Now my problem is how to make groups of checkboxes (into tables or in anything to make possible separating them, by horizontal bars for example).
This is a example of the lines of the file:
{"id": "v0", "namegroup": "Table rules create OR insert", "rule": "All classes give origin to a table.", "value": 0}
And this is how I create the array:
<?php
$file = fopen("rules.txt", "r") or exit("Unable to open file!");
$arrayRules = array();
$i = 0;
while(!feof($file))
{
$line = fgets($file);
$content = json_decode(utf8_encode($line), true);
$arrayRules[$i]['id'] = $content["id"];
$arrayRules[$i][0] = utf8_decode($content["rule"]);
$arrayRules[$i]['namegroup'] = $content["namegroup"];
$arrayRules[$i][1] = $content["value"];
$i = $i + 1;
}
fclose($file);
?>
And this is how I create the checkboxes:
echo "<input name=\"regra[]\" value=\"" . $arrayRules[$i]["id"] . "\" type=\"checkbox\" /> " . $arrayRules[$i][0] . "<br/> " ;
Remember that the user can edit the name of the group and all the other points.
As you can notice, my problem is not how to echo checkbox, but how will be the mechanism with the purpose of creating and organize the checkboxes by groups.
UPDATE1
For now I have this:
for($i=0; $i < count($arrayRules); $i++)
{
if ($arrayRules[$i]['idgroup'] == 1)
{
if ($arrayRules[$i][1] == 1)
echo "<input name=\"regra[]\" value=\"" . $arrayRules[$i]["id"] . "\" type=\"checkbox\" checked onclick=\"this.checked='checked'\"/> " . $arrayRules[$i][0] . "<br/> " ;
if ($arrayRules[$i][1] == 0)
echo "<input name=\"regra[]\" value=\"" . $arrayRules[$i]["id"] . "\" type=\"checkbox\" /> " . $arrayRules[$i][0] . "<br/> " ;
}
}
?>
the problem is that in if ($arrayRules[$i]['idgroup'] == 1) should not be the 1 but should be a variable or something that when every time it finds a new or a diferent name in the file on idgroup it add or create a new table/group of check-boxes.
Add group_id param to your json objects and resort all like
$arrayRules[$group_id][$i]
after, you can do something like:
foreach($arrayRules as $group_id=>$objects) {
// start group html
foreach($objects as $i=>$params) {
echo "<input name=\"regra[]\" value=\"" . $params[$i]["id"] . "\" type=\"checkbox\" /> " . $params[$i][0] . "<br/> " ;
}
// end group html
}

How do i email data from a form built with a while loop?

As part of a project I have a form in which our clients can edit a list of the keywords in which we work on as part of their SEO.
This is the code I use to display the keywords we have for them on our database
<?php
$c = true;
while($row = mysql_fetch_array($result))
{
$counter++;
echo "<div" .(($c = !$c)?' class="right"':'') . ">";
echo "<label for='keyword". $counter ."'>",
"<strong>Keyword " . $counter . " </strong></label>";
echo "<input type='text' name='keyword". $counter .
"' id='keyword". $counter ."' value='". $row['keyword'] . "' />";
echo "</div>";
}
?>
What I don't know what do do is collect the data when the form is submitted into an email.
I have the PHP mail bit ready but struggling on this a bit.
Any help?
I'd recommend changing the code to this:
<?php
$c = true;
while($row = mysql_fetch_array($result))
{
$counter++;
echo "<div" .(($c = !$c)?' class="right"':'') . ">";
echo "<label for='keyword". $counter ."'>",
"<strong>Keyword " . $counter . " </strong></label>";
echo "<input type='text' name='keyword[]' id='keyword". $counter ."' value='". $row['keyword'] . "' />";
echo "</div>";
}
?>
You can then access all keywords in the target php file for your form (after submission) using $_POST['keyword'], eg
foreach($_POST['keyword'] as $key => $value) {
echo "Keyword #". $key." value: ". $value."<br />";
// or your code to build your message
}
Instead of naming the inputs like "keyword1", "keyword2", etc, just name them all "keyword[]". When the form is submitted, PHP will aggregate them all into an array.
To use the POST data (make sure your form is using POST):
<?php
$message = '<ol>';
foreach($_POST as $key => $post) {
$message .= "<li><strong>Keyword " . $key . ":</strong>";
$message .= " <span>" . $post . "</span>";
$message .= "</li>";
}
$message .= '</ol>';
// mail the message here.
?>
Brian and Ergo summary are right, but if you don't want to modify the code inside the while loop you could, at the end of that, insert an hidden input that holds the last $counter value. Then in the target php file (where you will send the email), you can load the POST fields (modifying what Stephen wrote):
<?php
$counter = (int)$_POST['counter'];
$message = '';
for($i = 1; $i <= $counter; $i++){
$key = $_POST['keyword'.$i];
$message .= "<p>";
$message .= "<strong>Keyword " . $key . " </strong></label>";
$message .= "<span> " . $post . "</span>";
$message .= "</p>";
}
// mail message here.
?>

Categories