Making checkboxes take data along if checked to another page - php

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

Related

WordPress: Content in foreach remains on page because it does not refresh on form submission | Reload array after form submission?

I have tried the javascript refresh options on submit (on the <form> but none of them work. If I put the javascript refresh with the submit function, then every time it refreshes, the item gets sent to the database (do not want that).
What I have tried
onsubmit="location.reload()"
onsubmit="window.location.reload()"
onsubmit="setTimeout(function () { window.location.reload(); }, 10)"
It currently renders an array of items with a checkbox. When I click the checkbox, the item gets sent to the database as read -- but it stays on the screen (unless I revisit the page manually in the address bar). I am developing in WordPress using PHP.
Perhaps there is a small trick we can use just to remove the array that is sent on submit out of the books_array as soon as the submit button is clicked? Or reload the books_array after submission?
Here is my code:
form function
<form action="<?php user_add_new();?>" method="post">
<?php
foreach($books_array as $index => $i ) {
$s = $i->title;
$o = $i->listID;
$r = $i->submittedBy;
$d = $i->bookDESC;
$t = $i->id;
$current_user = wp_get_current_user();
$current_id = $current_user->ID;
if ($r == $current_user->ID || $r == 'administrator') {
echo '<div class="user-wrap">';
echo '<div class="inner-wrap">';
echo '<!---entire checkbox--->';
echo '<div><span class="check">';
echo "<input type='checkbox' name='checkbox[]' value='$index' onChange='this.form.submit()'>";
echo "<input type='hidden' name='item$index' value='$t'>";
echo "<input type='hidden' name='listID$index' value='$o'>";
echo "<input type='hidden' name='userID$index' value='$current_id'>";
echo '</span></div>';
echo '<!---entire checkbox--->';
echo '<!---info from book--->';
echo "<div><b>$s</b><br>$d</div>";
echo "<!---info from book--->";
echo '</div>';
echo '</div>';
}
};
?>
</form>
foreach loop
function user_add_new() {
global $wpdb;
$value = $_POST["checkbox"][0];
$bookTOadd = $_POST["item" . $value];
$listTOadd = $_POST["listID" . $value];
$userID = $_POST["userID" . $value];
$addTABLE = $wpdb->prefix . 'plugin_read';
$wpdb->insert(
$addTABLE,
array(
'bookID' => $bookTOadd,
'userID' => $userID,
'listID' => $listTOadd,
)
);
}
I keep running into issues, but I am so grateful to anyone who can give a little insight on how to approach this best. Thank you for taking the time to read this!
Problem fixed by creating a WordPress action and calling/rendering it only when the form is clicked (since before the action was rendered on page load just not executed until the click, which was 1 thing causing my issue re the not refreshing the entire page after form submission). No ajax (though its great with wordpress) nor .php files (that would just be a workaround).
Removed the action="" from my form, since we'll be using wordpress to do this.
Added this line <?php wp_nonce_field('book_send', 'book_send_nonce', true, true);?> to my form, you can see that below (this will help call my action in my WordPress file, associating it with this form)
<form method="post">
<?php wp_nonce_field('book_send', 'book_send_nonce', true, true);?>
<?php
foreach($books_array as $index => $i ) {
$s = $i->title;
$o = $i->listID;
$r = $i->submittedBy;
$d = $i->bookDESC;
$t = $i->id;
$current_user = wp_get_current_user();
$current_id = $current_user->ID;
if ($r == $current_user->ID || $r == 'administrator') {
echo '<div class="user-wrap">';
echo '<div class="inner-wrap">';
echo '<!---entire checkbox--->';
echo '<div><span class="check">';
echo "<input type='checkbox' name='checkbox[]' value='$index' onChange='this.form.submit()'>";
echo "<input type='hidden' name='item$index' value='$t'>";
echo "<input type='hidden' name='listID$index' value='$o'>";
echo "<input type='hidden' name='userID$index' value='$current_id'>";
echo '</span></div>';
echo '<!---entire checkbox--->';
echo '<!---info from book--->';
echo "<div><b>$s</b><br>$d</div>";
echo "<!---info from book--->";
echo '</div>';
echo '</div>';
}
};
?>
</form>
And this is my action (steps are described in the notes within the code) which makes the post when the action is called upon submit. It only submits the data after form validation. Once the data has been submitted, it then reloads the page using a built in WP function:
add_action('book_check', function() {
if ( ( is_single() || is_page() ) &&
isset($_POST[book_send_nonce]) &&
wp_verify_nonce($_POST[book_send_nonce], 'book_send')
) {
// form validation
function validate_book_data(){
$errors = new WP_Error();
if (isset($_POST[ 'item' ]) && $_POST[ 'item' ] !== '') {
$errors->add('item_error', 'Book not selected');
}
if (isset($_POST[ 'listID' ]) && $_POST[ 'listID' ] == '') {
$errors->add('list_error', 'No valid list this belongs to.');
}
if (isset($_POST[ 'userID' ]) && $_POST[ 'userID' ] == '') {
$errors->add('user_error', 'Not signed in');
}
return $errors;
}
// If form validation passes, send the info
$pass_validation = validate_book_data($_POST);
if ( $pass_validation ) {
$value = $_POST["checkbox"][0];
$data = array(
'userID' => $_POST["userID" . $value],
'bookID' => $_POST["item" . $value],
'list' => $_POST["listID" . $value],
);
global $wpdb;
// Select the table to post the data to
$book_checked = $wpdb->prefix . 'plugin_read';
// Insert the data to the table
$wpdb->insert($book_checked, $data, '%s');
// Set page refresh
$refresh_page = wp_redirect($_SERVER['HTTP_REFERER']);
// After data is inserted, refresh the page
wp_safe_redirect( $refresh_page );
// and exit
exit();
}
}
});
Using this action solves the issue of the page not refreshing because the action is only called when the checkmark is clicked and within the action, I refresh the page only after the data has sent.
I hope this will help anyone else with the issue. Coding from 8am-2am lately really had my brain become mush so the solution took me a short bit.

How run code when clicking on a looped button

I need to show a button for each value and do some function,
The following code is working for displaying the button only
but it doesn't show the result of the function after the button
$ids = [1,2,3,4,5,6];
foreach( $ids as $id ) {
$post_url = get_the_permalink($id);
echo $post_url."<input type='submit' name='doit' value='Change'><br>";
$doit = $_POST['doit'];
if(isset($_POST['doit'])){
echo get_post_field( 'post_name', $id)."<br>";
}
}
Can you try this solution?
I added an ID to the name field so when you click the button it runs only the if statement of this button.
Also make sure that the buttons are wrapped inside a form tag with a method attribute.
echo "<form method='post'>";
$ids = [1,2,3,4,5,6];
foreach( $ids as $id ) {
$post_url = "test.com";
echo "$post_url <input type='submit' name='doit_$id' value='Change'><br>";
if(isset($_POST['doit_'. $id])){
echo $id . "_RUNNING <br>";
}
}
echo "</form>";
Also $doit = $_POST['doit']; prints a NOTICE in php when it is not defined, it is better to check if $_POST['doit'] isset before assigning it to a variable.

interact with one object individually inside while loop

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

checkbox issues, can't get array to stay CHECKED on form submit

I've been trying to solve this problem for the last 3 hours and I'm getting close, but my inexperience is showing. I've tried all the permutations I can think of.
I have a form with checkboxes. The values are retrieved from mysql. The form is being submitted to the same page. You can view it live here. Type "Axminster" for the search.
The original checkbox code is as follows:
<?php
$categories_list = split('[
]', get_setting('categories', $db));
foreach ($categories_list AS $cat)
{
$cat = trim($cat);
echo "<input type=\"checkbox\" name=\"categories[]\" value=\"" . $cat . "\">" . $cat . "<br>";
}
?>
so I then submit the form and as normal I want the checkbox checked values to remain checked. For a dropdown box in my form I have used the code
<?php if($radius == $_POST['radius']) echo ' selected="selected"'; ?>
and this works perfectly, however I'm trying to use the following code to get the checked checkboxes to remain checked, and I'm having no luck:
<?php
$categories_list = split('[
]', get_setting('categories', $db));
foreach ($categories_list AS $cat)
{
$cat = trim($cat);
// I've added these two lines, and added " . $select . " to the input field.
foreach ($_POST['categories'] AS $category) {
if($cat == $category) { $select = "CHECKED"; } }
echo "<input type=\"checkbox\" " . $select . " name=\"categories[]\" value=\"" . $cat . "\">" . $cat . "<br>";
}
?>
The result is that every checkbox after the first checked checkbox is also being checked. For example I have four checkboxes and even if I check only the 2nd checkbox, the 3rd and 4th are also being checked on the next page.
I'm completely lost now. Please can anyone help. Thanks.
You could use
if(isset($_POST['categories']) && in_array($cat, $_POST['categories']))
You also need to reset the $select on each loop, or use an else{}, as once it is set using your foreach, the value never changes, so all checkboxes after the selected will be checked as well.
the code could now look like-
<?php
$categories_list = split('[
]', get_setting('categories', $db));
foreach ($categories_list AS $cat)
{
$cat = trim($cat);
// I've added these two lines, and added " . $select . " to the input field.
if(isset($_POST['categories']) && in_array($cat, $_POST['categories'])) { $select = "CHECKED"; }
else { $select = ''; }
echo "<input type=\"checkbox\" " . $select . " name=\"categories[]\" value=\"" . $cat . "\">" . $cat . "<br>";
}
?>

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