interact with one object individually inside while loop - php

I have a contact form inside a while loop, which will send an email to the user displayed in the while loop. But with this structure I would send an email to all objects inside the loop. I don't know how to escape the while loop in this case.
... while($row = $sql->fetchObject()){
... echo $row->userMail;
echo '<form ...><input name="contactMail"><...submit></form>';
if(isset($_POST['visitorMail']{
mail($toUserMail,$subject,$body_containsVisitorMail,$headers);
//this will send an email to all "objects" displayed in within the while loop -> problem
}
}

I suppose you need to check value of $_POST['contactMail'] with the current iterated one:
while($row = $sql->fetchObject()){
echo $row->mail;
echo '<form ...><input name="contactMail" value="' . $row->mail . '"><...submit>
<input type="hidden" name="itemId" value="' . $row->id . '"></form>';
if(isset($_POST['contactMail']) && $_POST['itemId'] == $row->id) {
mail($toRowMail,$subject,$body,$headers);
}
}

Related

PHP retrieve previous value after form submision inside loop

How can I retrieve selected value after form submision inside looped HTML select? I managed to solve the problem with manual if statements, but thats not dynamic.
I'm also storing previously submited value inside a cookie. I use self page form submit.
I managed to retrieve previous value from radio button:
<input type="radio" name="spol" value="moški" checked="checked" <?php if (isset($_POST['spol']) && $_POST['spol'] == 'moški') {
echo ' checked="checked"';
} ?>>
But can't find a way to do this inside foreach loop
<!---Cookie "keks" is storing previous submited string-->
<select name="status">
<?php
$_COOKIE['keks'];
$statusi = ["Dijak", "Študent", "Zaposlen", "Brezposelni"];
$counter= 0;
foreach ($statusi as $status) {
$counter++;
if ($counter == 2) {
echo "<option value=" . $status . " selected>" . $status . "</option>";
} else {
echo "<option value=" . $status . ">" . $status . "</option>";
}
}
?>
</select>
As stated in html comment, $_COOKIE['keks']; is storing the last value.
You might want to store that value into a variable or use it as is. and then, compare it against the current iteration of your loop.
$lastValue = $_COOKIE['keks'];
// some code
foreach ($statusi as $status)
{
if ($status == $lastValue)
// mark the option as selected
else
// don't mark it
}

Making checkboxes take data along if checked to another page

I'm trying to make a page which shows data from the database and I'd like to have checkboxes next to the data to select the data with the checkbox and take it to another page, currently how I display the data from the database and the checkbox is
foreach ( wc_get_order( $ordernumber )->get_items() as $item ){
echo "<input type='checkbox' name='productinfo[]' value='Yes'>"; echo '<p>';
echo __('Tuotteen nimi: ' ) . $item->get_name() . '<br>';
echo __('Määrä: ' ) . $item->get_quantity() . '<br>';
echo __('Tuotteen hinta: ' ) . wc_price($item->get_total()) . '</p>';
}
is it possible to make the checkbox take all that info with it on submit button press and take it to another page and display it there?
Feel free to ask if there's something unclear
Put your code inside form define that page in the action
<form action="demo.php" method="post">
<?php
foreach ( wc_get_order( $ordernumber )->get_items() as $item ){
echo "<input type='checkbox' name='productinfo[]' value='".$item->get_name(). $item->get_quantity() .$item->get_quantity()"'>";
}
?>
<input type="submit" name="submit">
</form>
Another file- where you want to send your data
<?php
$test = $_POST['productinfo'];
for($i=0; $i<sizeof($test); $i++) {
list($name, $quantity, $total) = explode(" ", $test[$i]);
echo "Name-".$name;
echo "Quantity".$quantity;
echo "Total".$total;
}
?>
You can perform any action to take out the data. In this case i am spliting up the data using space
This might not be the perfect solution
but it works
Hope it helps

Loop through form values from a dynamic php form

I building on top of an existing PHP based application to ability to update menu items name and prices.
I have generated a dynamic form which is populated with the results form the database. The idea is that the user can update the item name or price to update the information in the database.
The form works fine, but I am having dome trouble getting the info out of the form. each Item has a separate ID so I need to essentially do a foreach through the form and call the update function each time with the respective item id.
I can handle the DB side of things fine, but the application I am building on has a 'getInput' function to check input exists and to get the input form the form and I would like to use this.
This is the getInput function:
public static function exists($type = 'post') {
switch($type) {
case 'post':
return (!empty($_POST)) ? true : false;
break;
case 'get';
return (!empty($_GET)) ? true : false;
break;
default:
return false;
break;
}
}
public static function get($item) {
if(isset($_POST[$item])) {
return $_POST[$item];
} else if(isset($_GET[$item])) {
return $_GET[$item];
}
return '';
}
}
The problem I have is when calling this function it only returns the last item form the form. Is there a way i can iterate though the form and get each item?
This is the dynamic form and the getInput code so far:
$menuItems = DB::getInstance()->get('menu_items', array('cat_id', '=', $cat_id ));
if($menuItems->count()) {
echo '<form class="updateMenu" action="" method="post">';
echo '<table class="gridtable gridtableMenu">';
echo '<tr><th>Item Name</th><th>Item Price</th></tr>';
foreach($menuItems->results() as $item) {
echo '<tr>';
echo '<td class="menu-name"><input type="text" name="itemName" value="' . $item->item_name . '" required></td>';
echo '<td class="menu-price"><input type="number" step="any" name="itemPrice" value="' . $item->item_price . '" required></td>';
echo '<input type="hidden" name="id" value="' . $item->id . '">';
echo '</tr>';
}
echo '</table>';
echo '<input type="submit" name="updateMneu" value="Update Menu">';
echo '</form>';
} else {
echo '<div class="error">No items have been added to this menu</div>';
}
} // close categories foreach
} // close if category set
if(isset($_POST['updateMneu'])) {
echo Input::get('id'), '</br>';
echo Input::get('itemName'), '</br>';
echo Input::get('itemPrice'), '</br>';
} //close if isset updateMenu If
So I would like a foreach I think around this section:
if(isset($_POST['updateMneu'])) {
echo Input::get('id'), '</br>';
echo Input::get('itemName'), '</br>';
echo Input::get('itemPrice'), '</br>';
//update ite in the database, and move to gthe next item.
} //close if isset updateMenu If
I will handle data validation and what not later on.
As posted by 'noobHere' the answer was to set the input types name as arrays. e.g. name="itemName[]" instead of name="itemName"

PhP Radio button in Array

I have a form where you can select a radio button and it should transfer what was selected to the next page. My problem is that no matter which radio button you choose it always transfers the value associated last radio button over instead of the one you chose.
So if I choose Around the World it carries 5 with it instead of 10
I am required to use the GET method.
Here is my code:
$title = array("Around the World"=>"10","Coast to Coast"=>"7","The Big City"=>"5");
foreach($title as $sub=>$s_value) {
echo "$sub $$s_value";
echo '<input type="radio" name="sub" value="', $sub,'">';
echo "<br>";
}
if (empty($_GET["sub"])) {
} else {
$sub = sub_input($_GET["sub"]);
}
if (empty($_GET["s_value"])) {
} else {
$s_value = sub_input($_GET["s_value"]);
}
if (isset($title['sub'])){
$valid=false;
}
This is the code for the next page:
echo "<b>$sub</b><br />";
echo "Base Total: $ $s_value/mon x $month months <br />";
Yes I have omitted a lot of things, because everything else in my code is fine.
I tried doing this as well, adding in an unset() statement but it didnt work. It completely deleted the value variable....
$title = array("Around the World"=>"10","Coast to Coast"=>"7","The Big City"=>"5");
foreach($title as $sub=>$s_value) {
echo "$sub $$s_value";
echo '<input type="radio" name="sub" value="', $sub,'">';
echo "<br>";
unset($s_value);
}
//I also tried putting the unset here//
if (empty($_GET["sub"])) {
} else {
$sub = sub_input($_GET["sub"]);
}
if (empty($_GET["s_value"])) {
} else {
$s_value = sub_input($_GET["s_value"]);
}
if (isset($title['sub'])){
$valid=false;
}
You need to change the names of your variables $s & $s_value within the foreach loop. The foreach loop is setting these variables and they are then being accessed outside of the foreach loop if either of the GET values is empty such that there is no GET value to replace the contents of the variable. Therefore, it always uses 5 as the value because that is the last $s_value that you set.
In summary, changing $s & $s_value within the foreach loop to something like $key & $value respectively will fix your problem with the array value. Alternatively, you could unset them after the foreach loop but before the if statements.
In your current code, you just happened to switched the values on the loop. 10, 7, 5 are inside the elements, while the names Around The world... etc are inside the keys. You just need to switch them. Consider this example:
<?php
$title = array("Around the World"=>"10","Coast to Coast"=>"7","The Big City"=>"5");
if(isset($_GET['submit'], $_GET['sub'])) {
$sub = $_GET['sub'];
$name = array_search($sub, $title);
echo '<script>alert("You selected '.$name. ' => '.$sub.'");</script>';
}
?>
<form method="GET" action="index.php">
<?php foreach($title as $key => $value): ?>
<input type="radio" name="sub" value="<?php echo $value; ?>" /> <?php echo $key; ?> <br/>
<?php endforeach; ?>
<br/>
<input type="submit" name="submit" value="Submit" />
</form>

Assigning array elements to variables PHP loop

I have an array with the names of medication which the user is currently taking. On the webpage, I want to display radio buttons with the name of each of the medications, which are currently being taken, next to them. The code I have for the array is;
//Current Entries Section
$CurrentMedsQuery = "SELECT Name FROM `".$username."medication` WHERE Status='Current';";
$RunMedsQuery = mysql_query($CurrentMedsQuery) or trigger_error(mysql_error().$CurrentMedsQuery);
$Count = mysql_num_rows($RunMedsQuery);
$CurrentMedsArray = array();
while ($CurrentMedEntries = mysql_fetch_array($RunMedsQuery)) {
array_push($CurrentMedsArray,$CurrentMedEntries['Name']);
}
$session =& JFactory::getSession();
$session->set('CurrentMedsArray', $CurrentMedsArray);
while ($Count < 0) {
}
$FirstMedEntry = ($CurrentMedsArray["0"]);
Then on my HTML form, I have the following code which successfully displays the name of the first element in the array as I want it to;
<form method="post" name="currentmeds" action="">
<input type="radio" name="med1" value="med1"><?php echo $FirstMedEntry;?><br>
</form>
But my question is, I will not know how many current medication entries the user has, therefore I cannot continuously use echo $FirstMedEntry, echo $SecondMedEntry and so on..I figure I need some sort of loop, and help would be greatly appreciated!
Thanks in advance!
Changed to the following as suggested;
//Current Entries Section
echo '<form method="post" name="currentmeds" action="">';
$CurrentMedsQuery = "SELECT Name FROM `".$username."medication` WHERE Status='Current';";
$RunMedsQuery = mysql_query($CurrentMedsQuery) or trigger_error(mysql_error().$CurrentMedsQuery);
$Count = mysql_num_rows($RunMedsQuery);
$count = 1;
while ($CurrentMedEntries = mysql_fetch_row($RunMedsQuery)) {
echo '<input type="radio" name="med' . $count . '" value="med' . $count . '">' . $CurrentMedEntries . '<br>';
$count++;
}
echo '</form>';
But now receiving this error;
Notice: Array to string conversion in C:\xampp\htdocs\Joomla-Lifestyle\components\com_jumi\files\medication.php on line 238
Line 238:
echo '<input type="radio" name="med' . $count . '" value="med' . $count . '">' . $CurrentMedEntries . '<br>';
$CurrentMedsArray contains all your data, so you can just loop through it and display the values:
<form method="post" name="currentmeds" action="">
<?php foreach ($CurrentMedsArray as $key => $entry): ?>
<input type="radio" name="med<?=$key+1?>" value="med<?=$key+1?>"><?=$entry;?><br>
<?php endforeach ?>
</form>
If the array isn't needed for this purpose, this could be modified and displayed inside your while loop instead. Also note <?=$var;?> is the short syntax for <?php echo $var; ?>.
You don't need to use an array and I'd suggest you don't. Just do the following:
<?php
echo '<form method="post" name="currentmeds" action="">';
$CurrentMedsQuery = "SELECT Name FROM `".$username."medication` WHERE Status='Current'";
$RunMedsQuery = mysql_query($CurrentMedsQuery) or trigger_error(mysql_error().$CurrentMedsQuery);
$Count = mysql_num_rows($RunMedsQuery);
$count = 1;
while ($CurrentMedEntries = mysql_fetch_row($RunMedsQuery)) {
echo '<input type="radio" name="med' . $count . '" value="med' . $count . '">' . $CurrentMedEntries['name'] . '<br>';
$count++;
}
echo '</form>';
?>
Although I strongly urge you to not use mysql_. Instead, use mysqli_ or PDO.

Categories