Find the variable generated in loop of php - php

I have this php code:
for($i=0;$i<3;$i++) {
echo 'Question'.$i.'</br>';
echo 'Answer..</br>';
echo '<form action="" method="POST">';
echo '<textarea name="answer"></textarea>';
echo '</br><button name="answer_button'.$i.'"><b>Answer</b></button>';
echo '</form>';
}
Now I want to get the question number for which the answer_button is clicked.
Closest I could get was this:
for($i=0;$i<3;$i++) {
echo 'Question'.$i.'</br>';
echo 'Answer..</br>';
echo '<form action="" method="POST">';
echo '<textarea name="answer"></textarea>';
echo '</br><button name="answer_button"><b>Answer</b></button>';
echo '</form>';
if(isset($_POST['answer_button'])) {
echo $i;
break;
}
}
This gives me Question number but it will not print other questions in loop once the button is clicked.
Is there no solution without using javaScript?

This should work :
for($i=0;$i<3;$i++) {
echo 'Question'.$i.'</br>';
echo 'Answer..</br>';
echo '<form action="" method="POST">';
echo '<textarea name="answer"></textarea>';
echo '</br><button name="answer_button'.$i.'"><b>Answer</b></button>';
echo '</form>';
echo '</div>';
}
for($i=0;$i<3;$i++) {
if(isset($_POST["answer_button".$i])) {
echo $i;
}
}
Hope it helps.

Change the html markup to use an "array notation":
echo '<button name="answer_button['.$i.']" type="submit">Answer</button>';
That will cause php to populate an array when receiving back the form which you can examine:
<?php
// ...
if(isset($_POST['answer_button']) && is_array($_POST['answer_button'])) {
$id = array_shift(array_keys($_POST['answer_button']));
// ...
}
This allows to have multiple such buttons in a single form and detect which one has actually been clicked. It works, because $_POST will contain an array with a single element with key as in $id, which you can easily examine yourself with a var_dump($_POST); or similar.

I think this is what your looking for.
CODE
<?php
echo '<form action="" method="POST">';
for ($i = 0; $i < 3; $i++) {
echo 'Question: ' . $i . '<br>';
echo 'Answer..<br>';
echo "<textarea name='answer[$i]'> </textarea></br>";
echo "</br><button name='answer_button[$i]' value='BtnPushed'> <b>Answer</b></button><br>";
if (! empty($_POST['answer_button'][$i])) echo "Last Answer: {$_POST['answer'][$i]}<br>";
echo '<hr>';
}
echo '</form>';
Results

Related

How can I remove a value from my session array which is displayed within a table?

I have created an array within a session which I have sucessfully managed to place into a table. It is effectively just a list of favourties that a user can create by clicking a button on a product page.
However, I want to create a button next to each product in the table which removes the product from the array and I cannot work out why it isn't working.
Here is my code: (updated)
<?php
if (isset($_POST['remove'])) {
$value_to_delete = 'JX-1E1-LTU';
if(($key = array_search($value_to_delete, $_SESSION['arr'])) !== false) {
unset($_SESSION['arr'][$key]);
$_SESSION["arr"] = array_values($_SESSION["arr"]);
}
}
?>
<?php
$contents = ($_SESSION['arr']);
$arrlength = count($contents);
echo '<table class="table table-striped equipment">';
echo '<thead>';
echo '<tr>';
echo '<th scope="col">';
echo 'Parts';
echo '</th>';
echo '<th scope="col">';
echo 'Remove Item';
echo '</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
for($x = 0; $x < $arrlength; $x++)
{
echo '<tr>';
echo '<td>';
echo $contents[$x];
$part = $contents[$x];
echo '</td>';
echo '<td>';
$pos = array_search($part, $contents);
echo ' ' . $pos;
?>
<form action="" method="post">
<input type="text" name="value" value="<?php echo $part;?>">
<input type="submit" name="remove" value="Remove">
</form>
<?php
echo '</td>';
echo '</tr>';
}
echo'</tbody>';
echo '</table>';
?>
The 'deleteall' button works at the bottom of the page - it successfully removes all the values from my session, but the 'remove' button isn't removing each product individually:
if (isset($_POST['remove'])) {
$key=array_search($_GET[$part],$_SESSION['arr']);
if($key!==false)
unset($_SESSION['arr'][$key]);
$_SESSION["arr"] = array_values($_SESSION["arr"]);
}
echo '<form action="" method="post">';
echo '<input type="submit" name="remove" value="Remove">';
echo '</form>';
I'm guessing I am doing something wrong in the above section, but I seemed to have hit a brick wall and tried everything I can think of, any help would be gratefully recevied!
Your second sample seems to imply you're executing the remove action right before the form display, so after having displayed the table. It won't work on the first page refresh.
So unless the remove action code is not in the right place, Try this piece of code below, which works here.
Use it first as a single file. Follow the instructions, and see if you can reproduce your issue. If not, it might be related to the environment.
Then, put the block code before displaying your table (and edit the $_SESSION["arr"] with correct values :)), and see if it removes the right element from the array.
If it doesn't, try debugging it through logging.
<?php
session_start();
echo "<pre>";
// Load this page once. Then, before the next page refresh,
// Comment the below line to check if the session values
// are updated
$_SESSION["arr"] = array("trousers", "blue", "jean");
print_r($_SESSION);
unset($_SESSION["arr"][array_search("blue", $_SESSION["arr"])]);
print_r($_SESSION);
$_SESSION["arr"] = array_values($_SESSION["arr"]);
print_r($_SESSION);
echo "</pre>";
?>

PHP: how to place value from form to array

i am trying to do within PHP page.I have form which contains radio button and i want to get their value and place in array. I dont know where i am doing wrong.
code:
$example = array();
$i=0;
while($row = mysql_fetch_array($query) or die(mysql_error())){
$a= $row['A'];
echo '<form method="get" action="?page=".$next."">';
while ($row=mysql_fetch_array($query))
{
echo '<div class="boxed" >';
echo "\t".'<tr><th>'.
$row['question']."<br>".
'</th><th>'."<input type='radio' name= 't[]' value='{$row['A']}'>".$row['A']."<br>".
'</th><th>'."<input type='radio' name='t[]' value='{$row['B']}'>".$row['B']."<br>".
'</th><th>'."<input type='radio' name='t[]' value='{$row['C']}'>".$row['C']."<br>".
'</th><th>'."<input type='radio' name='t[]' value='{$row['D']}'>".$row['D'].'</th>
</tr>';
echo '<input type="hidden" name="page" value="'.$next.'">';
echo '<input type="submit" name="submit"/>';
$i++;
echo '</div>';
echo '</div>';
}
echo '</form>';
if (isset($_GET['submit'])) {
$example[] = $_GET['t'];
echo $example . 'chk';
}
}
replace .$example=$_GET['t']; $example itself a be array. you can process it as you need
if (isset($_GET['submit'])) {
$example[] = $_GET['t'];
echo $example . 'chk';
}
to
if (isset($_GET['submit'])) {
$example = $_GET['t'];
for($i=0;$i<sizeof($example);$i++){
echo $example[$i]."<br>";
}
}
or you can use foreach also
if (isset($_GET['submit'])) {
$example = $_GET['t'];
foreach ($example as $value) {
echo "$value <br>";
}
}

Function not Inserting Values in wordpress

function name_to_match($nametocheck){
global $wpdb,$namematch,$nomatchfound;
$query="select * from currency";
$namematch=$wpdb->get_col($query,1);
//echo $namematch;
foreach($namematch as $namet){
//echo $name;
if($namet == $nametocheck){
echo "Name Already Exists<br />";
$nomatchfound=0;
}
}
}
function add_signal_form(){
global $wpdb,$insert,$nametocheck;
echo "<br /><br /><br />";
$nametocheck=trim($_POST['name']);
$sign=trim($_POST['sign']);
$status=$_POST['status'];
if(isset($_POST['submit'])){
//..................Function to call if name exist it will not add
name_to_match($nametocheck);
if($nomatchfound ==0){
echo "Match Found";}
else
{
$insert= $wpdb->insert('currency',array('name'=>$nametocheck,'sign'=>$sign,'status'=>$status));
if(!$insert){
echo "Currency Not Added Query Fails";
}
else
{
echo "Currency Successfully Added";
}
}
}
echo '<form name="form1" method="post" action="">';
echo '<div class="label">';
echo '<label for="name">Name</label>';
echo '<div class="field">';
echo '<input type="text" name="name" id="name">';
echo '</div>';
echo '<div class="label">';
echo '<label for="sign">Sign</label>';
echo '</div>';
echo '<div class="field">';
echo '<input type="text" name="sign" id="sign">';
echo '</div>';
echo '<div class="label">';
echo '<label for="status">Status</label>';
echo '</div>';
echo '<div class="field">';
echo '<select name="status" id="status">';
echo '<option value="1">Publish</option>';
echo '<option value="0">Draft</option>';
echo '</select>';
echo '</div>';
echo '<div class="submit">';
echo '<input type="submit" name="submit" id="submit" value="Save Currency">';
echo '</div>';
echo '</p>';
echo '</form>';
/*
echo "<form action='' name=form1\" id=\"form1\" method=\"post\">";
echo '<input type="text" name="text" id="text">';
echo '<input type="submit" name="submit" value="Add New Signal">';
//wp_dropdown_pages();
echo "</form>";
*/}
This function working properly if name exist it return exists but when it not exist nothing happen no else clause fire what is the problem. I am doing something wrong . i want after checking it submit the form and show success message when currency added but nothing happening i try whole the day long and at last i fails in it suggest me
As #akirk suggested, you're never setting $nomatchfound to true or 1 in your name_to_match function.
But there are some other things you could do to make the code clearer and quicker. For example, name_to_match could return a value, instead of setting a global variable. And you could use the database to check for $nametocheck, rather than looping over all the values in the table - it'll make your code shorter and it'll run quicker. So I'd change name_to_match to something like this:
function name_to_match($nametocheck){
global $wpdb;
$query = $wpdb->prepare("select count(*) from currency where name = %s", $nametocheck);
$matching_row_count = $wpdb->get_var($query);
return $matching_row_count;
}
Then the start of your add_signal_form function becomes
function add_signal_form(){
global $wpdb;
echo "<br /><br /><br />";
$nametocheck=trim($_POST['name']);
$sign=trim($_POST['sign']);
$status=$_POST['status'];
if(isset($_POST['submit'])){
$existing_rows = name_to_match($nametocheck);
if($existing_rows != 0){
echo "Match Found";
}
else {
$insert= $wpdb->insert('currency',array('name'=>$nametocheck,'sign'=>$sign,'status'=>$status));
if (!$insert) {
echo "Currency Not Added Query Fails";
}
else {
echo "Currency Successfully Added";
}
}
}

Can not get PHP to post info to database

I've written a script to post information into my database for I can't get it to post and need help pointing out what I'm missing.
my php post for looks like this:
$query = "SELECT * from departments";
$res = mysql_query($query);
echo '<div id="department" >';
echo '<form action="depedit.php" method="post">';
echo '<input type="text" placeholder="Search departments">';
echo '<br>';
echo '</form>';
echo '</div>';
echo '<div id="depadd">';
echo '<form>';
echo '<table width="0" border="0">';
echo '<tr>';
echo '<td>Name:</td>';
echo '</tr>';
echo '<tr>';
echo '<td>';
echo "<select name='depid'>";
while ($row = mysql_fetch_array($res)) {
echo "<option value='".$row['id']."'>".$row['depname']."</option>";
}
echo "</select>";
echo '</td>';
echo ' </tr>';
echo '<tr>';
echo '<td> </td>';
echo '</tr>';
echo ' <tr>';
echo '<td><label class="limit">Select Limit for active courses in Learning Locker:</label></td>';
echo ' </tr>';
echo ' <tr>';
echo '<td>';
echo "<select name='courselimit'>";
echo "<option value='1'>1</option>";
echo "<option value='2'>2</option>";
echo "<option value='3'>3</option>";
echo "<option value='4'>4</option>";
echo "<option value='5'>5</option>";
echo "<option value='0'>Unlimited</option>";
echo "</select>";
echo '</td>';
echo '</tr>';
echo '<tr>';
echo '<td> </td>';
echo '</tr>';
echo '<tr>';
echo '<td><input type="radio" id="1" name="senabled" value="1"/><label for="c1" class="required">Required<br>(Study Shredder Feature Enabled)</br></label></td>';
echo '<td><input type="radio" id="0" name="senabled" value="0"/><label for="c1" class="optional">Optional</label></td>';
echo '</tr>';
echo '<tr>';
echo '<td><input type="hidden" name="orgid" value="'.$adminorgid.'"></td>';
echo '</tr>';
echo '<tr>';
echo '<td><input type="hidden" name="createdby" value="'.$userid.'"></td>';
echo '</tr>';
echo '<tr>';
echo '<td><input type="hidden" name="timecreated" value="'.time(now).'"></td>';
echo '</tr>';
echo '<tr>';
echo '<td> </td>';
echo '</tr>';
echo ' <tr>';
echo ' <td><button type="submit" class="btn">Submit</button></td>';
echo ' </tr>';
echo '</table>';
echo "</form>";
echo '</div>';
depedit.php looks like this:
$adddep = "INSERT INTO organization_dep (orgid,depid,courselimit,senabled,createdby,timecreated) VALUES ('".$_POST["orgid"].",".$_POST["depid"].",".$_POST["courselimit"].",".$_POST["senabled"].",".$_POST["createdby"].",".$_POST["timecreated"]."')";
$res = mysql_query($adddep);
if ($res === TRUE) {
echo "Department added successfully";
} else{
printf("Could not create department");
}
the correct information seems like its getting passed as the url displays the following information in it:
/index.php?depid=6&courselimit=3&senabled=1&orgid=9&createdby=1129&timecreated=1364005206
any help with this would be greatly appreciated as I'm sure its something simple that I'm just over looking.
You want to get the values from the $_POST
('".$_POST["orgid"].",".$_POST["depid"].",".$_POST["courselimit"].",".$_POST["senabled"].",".$_POST["createdby"].",".$_POST["timecreated"]."')";
but your saying it is passed through the URL, this looks like you need to use $_GET to get the values
--- and one small tip you can use echo to print multiple lines it works. as long as you close it, in the end
e.g
echo " <html>
<body>
</body>
</html>
";
I think you have a bunch of things to get right before this will be working:
Only the first form, which seems to be for searching departments, have method and action attributes
Since the second form does not have the action attribute, it is not submitting to depedit.php but to the same page that has the form.
Since the second form does not have the method attribute, it defaults to GET, and you are trying to read out POST variables in your PHP. If it was not using GET, you would not see those params in the resulting URL.
In your SQL insert statement, you must have single quotes around every single text value but not around int values. Now you have one single quote before the first value and one before the last which makes no sense.
First: this portion will not be POSTed "depedit.php" because there is no submit
echo '<form action="depedit.php" method="post">';
echo '<input type="text" placeholder="Search departments">';
echo '<br>';
echo '</form>';
Second: this will never be POSTed to depedit.php, since your <form> does not have an action specifying "depedit.php"
echo '<form>';
echo '<table width="0" border="0">';
echo '<tr>';
//other codes
echo "</form>";
maybe you mean to remove the first echo '</form>'(line 7) and the second <form>(line 10)

PHP and Session error

Hello I have a problem with a session. When I use a session to pass a variable to another page the values of that variable always still the same in the other page. No matter what row I selected. When I change the "action" to the same page where the variable is, the value shows correct. Sorry for my bad English if someone speak Spanish let my know to explain better. I really need help in this.
Here is my code:
<?php
include_once 'rnheader.php';
session_start();
$ticket_select = $_POST['serviceID'];
echo ' Create Service ';
echo '<table border="1" >';
echo '<tr>';
echo '<th>Service ID</th>';
echo '<th>Title</th>';
echo '<th>Description</th>';
echo '<th>Notes</th>';
echo '<th>Submit By</th>';
echo '<th>Assigned Employee</th>';
echo '<th>Assigned Group</th>';
echo '<th>Category</th>';
echo '<th>Status</th>';
echo '<th>Urgency</th>';
echo '<th>Customer</th>';
echo '<th>Day Created</th>';
echo '</tr>';
$query = ("SELECT ServiceID, Title, Description, Notes, SubmitBy, AssignedEmp, " .
"AssignedGroup, NameCategory, TipoStatus, TiposUrgencia, CustomerName, DayCreation FROM Service");
$result = queryMysql($query);
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td><form method ="post" action="rnservices1.php">';
?>
<input type="submit" name="serviceID" value=<?php echo $row['ServiceID']?>
<?php
echo '</form>';
echo '<td>'.$row['Title'].'</td>';
echo '<td>'.$row['Description'].'</td>';
echo '<td>'.$row['Notes'].'</td>';
echo '<td>'.$row['SubmitBy'].'</td>';
echo '<td>'.$row['AssignedEmp'].'</td>';
echo '<td>'.$row['AssignedGroup'].'</td>';
echo '<td>'.$row['NameCategory'].'</td>';
echo '<td>'.$row['TipoStatus'].'</td>';
echo '<td>'.$row['TiposUrgencia'].'</td>';
echo '<td>'.$row['CustomerName'].'</td>';
echo '<td>'.$row['DayCreation'].'</td>';
echo '</tr>';
}
mysqli_free_result($result);
echo $ticket_select;
$_SESSION['serviceID'] = $ticket_select;
'</table>';
?>
Is it a case issue?
$_SESSION['serviceID'] = $ticket_select;
<input type="submit" name="serviceID" value=<?php echo $row['ServiceID']?>
$ticket_select = $_POST['serviceID'];
Notice the middle one has a capital S on ServiceID and the other two are serviceID.

Categories