Dynamically Generated delete button - php

I'm new to php and I was wondering how I would be able to create something like a delete button for deleting items in a list that would be generated from a dynamically growing array.
An example of what I mean is this:
<?php
if (isset($_REQUEST['foo']))
{
if (isset($_SESSION['words']))
{
$_SESSION['words'][] = 'added word';
}
else
{
$_SESSION['words'] = array('cat', 'dog', 'you', 'me');
}
foreach ($_SESSION['words'] as $key => &$value)
{
echo "<p>" .
$value .
" - <input type='submit' name='delete_" .
$value .
"' value='Delete Entry' /></p>";
}
if (isset($_REQUEST['clear']))
{
session_destroy();
}
?>
Where, on every button click that gets sent to my script it would echo out the array with the buttons.
I'd like to link the delete buttons to a function that looked something like:
function delete_entry( $index )
{
unset($_SESSION['words'][$index]);
$_SESSION['words'] = array_values($_SESSION['words']);
}
Is what I'm asking even possible?

Your array of words seem to be stored in your session variable, so I'm assuming that you want to remove/add words to it. How about this...?
Have a separate form for each word with a hidden field saying what the word is:
So in the for loop:
echo "<form><p>".$value." - <input type='submit' value='Delete Entry' /></p><input type=\"hidden\" name=\"delword\" value=\"".$value."\"/></form>";
if(isset[$_REQUEST['delword']]) remove it from the session array (do this before you do your echoing for loop. (You could use array_search to find the element, then run unset as you suggested)
Let me know if you want me to elaborate on this suggestion.

Related

form post of values in array and manage them divided by key

I dont know how to manage this situation, I'm a noob coder, I have a page that shows you all available lots where you can unload a specific item from that lot.
This is the foreach that prints out:
$lotto, $totalelotto, $data, and ask for qtyvalue to unload from $lotto (input can be also NULL)
foreach ($dataslotto as $data) {
$totalelotto = totlotto($database, $data['lotto']);
$lotto = $data["lotto"];
$data = $data["data"];
echo "<tr>";
echo "<td>".$lotto."</td>";
echo "<input type=\"hidden\" value=\"".$lotto."\" name=\"array[]\" />";
echo "<td>".$totalelotto."</td>";
echo "<input type=\"hidden\" value=\"".$totalelotto."\" name=\"array[]\" />";
echo "<td>".$data."</td>";
echo "<input type=\"hidden\" value=\"".$data."\" name=\"array[]\" />";
echo "<td><input type=\"text\" class=\"form-control\" placeholder=\"Qta.\" required name=\"qtyvalue\"></td>";
echo "</tr>";
}
I dont know how to set name="" of input fields (because the number of fields can change if there are many lots) and I dont know how to send $_POST data as array, and then foreach group of $lotto, $totalelotto, $data, $qtyvalue where is set $qtyvalue do another query.
I put it in no regular code, I know it looks bad but it's just for giving you an idea.
$_POST[''formarray];
foreach ( /* values recieved in each <tr> inside formarray where $_POST['qtyvalue'] is not empty */ ){
#EXECUTE THIS
}
Thanks for help!!
And sorry for my bad coding skills.
$_POST is an Associative/Key Value pair, it's key is whatever is set as the inputs name.
so if you wanted to send the users input username to the backend PHP script
You set the value and it's name
<input type="text" name="username" value="User123">
then to retrieve the user name you can do
print_r($_POST["username"]);
to print the value.
So you ask how do you loop over each one in $_POST, that's pretty simple you can could a foreach loop over the entire $_POST array.
foreach($_POST as $key => $value)
{
//check something has been entered for the current value we are iterating over
if($value != null)
{
print_r($key . " value is : " . $value);
}
}
this would loop over each item in the $_POST array with key being set to whatever the DOM elements name is.
Don't forget the $_POST array is just that an array, you could do
var_dump($_POST);
and see everything that was sent in the POST request.
You can use array names for your inputs. Say you have a row of your table like this:
<tr>
<td><input ... name="lotto[]"></td>
<td><input ... name="totalelotto[]"></td>
<td><input ... name="data[]"></td>
<td><input ... name="qtyvalue[]"></td>
</tr>
Then you will get arrays $_POST['lotto'], $_POST['totalelotto'] and so on, each with the same number of elements, and elements with same index belonging to one row of the table. You could then process those elements like this
foreach ($_POST['lotto'] as $i=>$lotto) {
if ($_POST['qtyvalue'][$i] > 0) {
...
}
}

php looping out form match new value with id?

I'm looping out a form for every thing in the database write out it's position as and also its id.
foreach ($foo as $thing) {
$HTML = "
<input type='text' value='$thing->position' name='newPosition[]'/>
<input type='hidden' value='$thing->id[]' name='id'/>";
}
On submit i want to extract everyones id and new position so i can change it in the database.
How to i extract everyones position with their id??
somehow return $_POST['newPosition'] and loop it to changes everyones position value in the database (thats not a problem), my problem is how to match it with its id?
You can name the position fields with id -
<input type='text' value='$thing->position' name='newPosition[$thing->id]'/>
After posting the data -
foreach($posted_data['newPosition'] as $id => $position) {
echo $id.' - '.$position;
}
You could do it like this
foreach ($foo as $thing) {
$HTML = "
<input type='text' value='$thing->position' name='newPosition[" . $thing->id . "][]'/>
<input type='hidden' value='$thing->id[]' name='id'/>";
}
and then when you get the data you just get the key as well
like so
foreach($array as $key => $value){}
That way newPosition is tied with the ID :)

Store checkbox group values as a variable

I am trying to store the values of selected checkboxes on a multi page form so I can include these on the final page of the form (and in the email that is sent to the site owner).
I have worked out how to display the values, but saving them for later has got me stumped. I'm learning as I go so I wouldn't be surprised if this is quite easy...
This is the code I'm using:
<?php foreach ($_POST['fooby'] as $key => $entry) {
if(is_array($entry)){
print $key . ": " . implode(',',$entry) . "<br>";
}
else {
print $key . ": " . $entry . "<br>";
}
} ?>
And this is the result I get:
1: Minor Service £129
2: plus MOT £35
That's exactly what I'm after - though I don't need the numbers at the beginning. How do I save that information for later?
With the updated code below, I now get the following result:
Minor Service £129
plus MOT £35
That's perfect, but I'm struggling to work out how to store that information to a session variable. I should point out that the values returned from the form are dynamic and unknown beforehand. There might also be 10 items in the array, not just the two shown above.
What I have so far:
<?php if (isset($_POST['fooby'])){
foreach ($_POST['fooby'] as $entry) {
if(is_array($entry)){
$dokval = implode(',',$entry) . "<br>";
echo $dokval; //echoes the expected result on the page
$_SESSION['dokvalues'] = $dokval; //only stores the last item
}
else {
print $entry . "<br>"; //not rewritten this part yet
}
}
} ?>
Simply insert these values in hidden input elements in a form on the following pages to use them again:
<input type="hidden" name="<?php echo $key1; ?>" value="<?php echo $value1; ?>" />
<input type="hidden" name="<?php echo $key2; ?>" value="<?php echo $value2; ?>" />
...
The foreach loop iterates through the array and for each iteration $key variable is the current index and $entry is the value of that index. The numbers in the list are just representation of index values. If you don't need them, you can go for this:
<?php foreach ($_POST['fooby'] as $entry) {
if(is_array($entry)){
print implode(',',$entry) . "<br>";
}
else {
print $entry . "<br>";
}
} ?>
The keys will still stay in $_POST['fooby'] array.
The variable $entry holds one value of the array each time the foreach loop iterates. So the variable $dokval will also hold only one value, which it echos each time the loop iterates. By the time you look at the session variable it's value is going to be the last value that $dokval held. Make $dokval an array and push the $entry value into it. array_push. Also, make sure you start a session at the beginning of every page you want to use the $_SESSION variable.
Jeff

PHP - odd one out

I am trying to create a "find the odd word" application (given a list of words like cat, dog, bird and car, the latter is the odd one because it's not an animal).
Firstly, I retrieve and shuffle randomly five words from the DB. They are called: odd (which is the odd one), one, two, three, four (which are the other four).
Then, I produce a form (radio button) with the five words, so that users can select one of their choice:
$words = array
(
$odd,
$one,
$two,
$three,
$four,
);
shuffle($words);
foreach ($words as $word)
{
$string = $word;
echo '<html><input type="radio" name="odd" value="'.$string.'">'.$string.'<br><br></html>';
}
In the next PHP page, I want to check if the selected word is the odd one. I can't figure out how to do it.
Any suggestions? Thanks!
Use the $_SESSION variable to handle this to find out if the odd was selected or not
Say the following code is from your Odd.php that displays the radio buttons (assuming you would handle the form element and submit button)
<?php
session_start();
$_SESSION['odd'] = $odd;
$words = array
(
$odd,
$one,
$two,
$three,
$four,
);
shuffle($words);
echo '<form method="POST" action="Next.php">';
foreach ($words as $word)
{
$string = $word;
echo '<input type="radio" name="odd" value="'.$string.'">'.$string.'<br><br>';
}
echo '<input type="submit" /></form>';
?>
On your Next.php file use the code below to validate if the odd was selected or not
<?php
session_start();
$odd = $_SESSION['odd'];
if ($_REQUEST['odd'] == $odd) { // $_REQUEST handles both $_POST and $_GET
echo "Odd was selected";
} else {
echo "Odd was not selected";
}
?>
Hope this helps!
You need to carry the odd word to the next page somehow. There are many different ways of doing this, arguably the easiest one is by saving the odd word in a variable in your form
<input type="hidden" name="realodd" value="<?php print $odd; ?>" />
On the next page, you can then check whether the chosen word is right by comparing it to the hidden word.
if ($_POST['realodd'] == $_POST['odd']) {
print "You found the odd word.";
}
This could easily be broken by just looking at the source code. A better solution could be saving the odd word in a session cookie:
session_start();
$_SESSION['realodd'] = $odd;
And then verify on the next page almost like before
if ($_SESSION['realodd'] == $_POST['odd']) {
print "You found the odd word.";
}
session_start();
if(isset($_POST['odd'])&& isset($_SESSION['odd'])&& $_POST['odd']==$_SESSION['odd']){
exit ("You're a genius, you got the right word");
}else{
if (isset($_POST['odd'])){ echo "Sorry, try again";}
}
//sql query goes here
$words = array
(
$odd,
$one,
$two,
$three,
$four,
);
$_SESSION['odd'] = $odd;
shuffle($words);
echo '<form method="POST">';
foreach ($words as $word)
{
echo '<input type="radio" name="odd" value="$word"/>$word<br><br>';
}
echo '<input type="submit" value="Submit"/>';
echo '</form>';

Showing each quiz inquiry separately

I am trying to make a quiz using PHP and Mysql. I have create my database and filled it. The database is construct as follows: question_id(P.K),question, right answer, annswer1,answer2, answer3,level and test_id(F.K).
I have created a query that "draws" questions in a random order and I have shuffled the answers. The PHP script for showing the Qs and As to the user is the following:
while ($index <= (count($test)-1)){
echo $test[$index]['question']. "<br/>";
$question_id=$test[$index]['question_id'];
$s_ans=User_Model::shuffle_answers($question_id);
foreach ($s_ans as $s_a){
echo "<input type='radio' name='test_ans[$index][$s_a]' id='$question_id' />$s_a <br />";
}
echo "<hr/>";
$index++;
}
The above code shows all questions and their answers at once.
What I would like to do, and couldn't successfully get it done, is to show each question separately and when the user presses the "next" button, the next question accompanied by its answers will be shown to him.
So,
a)is there a way I can achieve that?
b)when I try to access user's answers I get the following output:
Array ( [0] => Array ( [I like ice cream => on ) [1] => Array ( [i don't go to school] => on ) [2] => Array ( [i play basketball] => on ) [3] => Array ( [i like sailing] => on ) )
How can i access the user's answers as to compare them with the right answer?
Well, since you're using PHP you can use sessions or cookies. It's probably not the most elegant solution, but I'd generate a reference string that represents a sequence of questions and store it in one session or cookie variable, and then have another session or cookie variable that represents the current position in the quiz. Furthermore you could have additional variables to keep track of score and other tidbits. Then when they hit the next button you just update variables and display the next question, or the end of the quiz if you've reached it.
If you want to do it dynamically without having to load another page then you'll need to look into javascript.
Multipage quizzes are very easy to do.
A) This can be done by removing the while() loop, but leave the counter to pass through a hidden <input> OR increasing the $_SESSION variable
$index = $_POST['index'] // OR $_GET['index'] OR $_SESSION['index'] depending on your form method
echo $test[$index]['question']. "<br/>";
$question_id=$test[$index]['question_id'];
$s_ans=User_Model::shuffle_answers($question_id);
foreach ($s_ans as $s_a){
echo "<input type='radio' name='test_ans[$index][$s_a]' id='$question_id' />$s_a <br />";
}
if ($index < $total_questions){
$index++; // Increase var, and then use in hidden input
echo "<input type='hidden' name='index' value='$index' />";
echo "<input type='submit' name='submit_answer' value='Next' />";}
else {
echo "<input type='submit' name='submit_answer' value='You Are Done' />";}
//OR
$_SESSION['index'] = $index++;
B) Without your code, this is just an example -
if ($user[$index]['their answer'] == $test[$index]['right answer'])
{ echo "You were correct";}
else
{ echo "Sorry, your answer was incorrect";}

Categories