How run code when clicking on a looped button - php

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.

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.

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

cookie value back into input fields

i'm actually new to PHP so i need your help!
I'm using a table within a form, and SQL Server to fill the table rows.
The form starts with an input field for quantity input type="number".
<form name="testform" method="post" action="submit.php">
<?php
$sql="query goes here";
$query=sqlsrv_query( $conn, $sql, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
if ($query) {
while($row = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC) ) {
echo "<td><input type='number' name='quantity[]'></td>";
}
}
?>
</form>
After submitting the form, i want the user to have the possibility to navigate back to the previous page to change the quantity input if possible.
So i need to restore the input values when navigating back (all values are now lost when navigating back).
I found this way by using the Cookies to store the input values so i found a way to store all values of input name='quantity[]' (array) in the cookies. And print them on the page when navigating back. It prints all values correct with the correct array index position as well.
Here's some of the code:
On my form page (form.php) for receiving cookies.
<?php
if (isset($_COOKIE['Cookie_Info'])){
$cookie = $_COOKIE["Cookie_Info"];
$cookie = stripslashes($cookie);
$savedAantArray = json_decode($cookie, true);
echo '<pre>';
print_r($savedAantArray); echo '</pre>';
} else {
$data = array(
'quantity[]' => ''
);
}
?>
On my submit page (submit.php) for setting cookies, with link to return to form.php page.
<?php
if (isset($_POST['submit'])) {
$post_arr = $_POST;
$expire = 8*3600;
setcookie("Cookie_Info", serialize($post_arr), time()+$expire);
}
?>
Make Some Changes..
Result when returning to form.php
Cookies
Array
(
[quantity] => Array
(
[0] => 8
[1] => 8
)
[submit] => Submit
)
Here's my question:
Is there a way to store those values from the array into all the right input fields?
Instead of printing them just as an array (which is not what i want, but i wanted to test the cookie storage).
Thanks in advance!
Thanks Yvon, got it working now.
Again on my second page:
<?php session_start();
$_SESSION['quantity'] = $_POST['quantity'];
foreach($_POST['quantity'] as $key => $value) {
echo "<input name='quantity' value='$value'>\n<br />";
}
?>
Back to first page:
<?php session_start();
$quantity=$_SESSION['quantity'];
print_r($quantity);
echo "<br \>";
foreach($_SESSION['quantity'] as $key => $value) {
echo "<input name='quantity[]' value='$value'>\n<br />";
}
?>
Just a small edit, got it working perfect now (including printing the correct amount of rows).
On the first page:
<form name="form" method="post" action="second.php">
<?php session_start();
include 'db_connect.php';
$quantity=$_SESSION['quantity']; print_r($quantity); echo "<br \>";
$sql ="SELECT * FROM X0ONTDTA.WEBRELGB";
$query = sqlsrv_query( $conn, $sql, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
if($query){
if (isset($_SESSION['quantity'])){
foreach($_SESSION['quantity'] as $key => $value) {
echo "<input name='quantity[]' value='$value'>\n<br />";
}
}
elseif($query){
while($row = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC) ) {
echo "<input name='quantity[]' value=''>\n<br />";
}
}
}
?>
<input type="submit" value="Submit" name="submit"></input>
</form>
On the second page:
<?php session_start();
$_SESSION['quantity'] = $_POST['quantity'];
foreach($_POST['quantity'] as $key => $value) {
echo "<input name='quantity' value='$value'>\n<br />";
}
echo "<pre>";
print_r($_POST['quantity']);
echo "</pre>";
?>
Go Back
Resulting in this:
after submit
going back

How send some info (values) in a link (<a>) to another page?

I have a page which generates a list of games and button for each game with value "BUY GAME".
The objective is to execute multiple SQL queries when the button is clicked for a particular game.
What is an appropriate way of accessing the 'name','consolename',etc. for EACH game from the ARRAY and to execute queries on them in another page - purchase.php?
NOTE: I did consider using sessions but when I pass the variable $index as a SESSION variable, I only get the final value at all times.
buygame.php
<?php
session_start();
//connect to db
dbConnect("root", "") ;
dbSelect("webdesign");
//SEARCH FOR GAMES
print "<h3>Games to Buy: </h3>";
$query = "SELECT gamecode,name, consolename,price, points, genre from game";
$result = runQuery($query);
while($row = mysql_fetch_array($result))
{
$array[] = $row;
}
$index =0 ;
//DISPLAYING A LIST OF GAMES
while($index<sizeof($array))
{
echo $array[$index]['name'];
echo $array[$index]['consolename'];
echo $array[$index]['genre'];
echo ("Price is: ".$array[$index]['price']." USD");
echo ("Loyalty Points: ".$array[$index]['points']);
//THE BUTTON "BUY GAME"
echo("<a href='purchase.php'><input type='submit' name='submit[$index]' value='Buy Game'/></a>");
$index = $index + 1;
}
?>
purchase.php
<?php
session_start();
//connect to database
dbConnect("root", "") ;
dbSelect("webdesign");
$index = 0;
echo "Button clicked ";
//I am trying this but I'm sure that this is not right
if (isset($_POST['submit[$index'])){
print "$index was clicked";
}
?>
In buygame.php change the code to:
//THE BUTTON "BUY GAME"
echo("<a href='purchase.php?gamecode={$array[$index]['gamecode']}'><input type='submit' name='submit[$index]' value='Buy Game'/></a>");
In purchase.php
<?php
if(isset($_GET['gamecode'])) {
echo $_GET['gamecode'];
//and make ......
}
//THE BUTTON "BUY GAME"
$gamecode = $array[$index]['gamecode'];
echo("<a href='purchase.php?gamecode=$gamecode'><input type='submit' name='submit[$index]' value='Buy Game'/></a>");
$index = $index + 1;
Then in purchase.php You know exactly, what game has been bought.

I want to increment a value from outside a php block

Basically its a web page where someone would press a button to increment the $selection variable. Globals and statics do not seem to work.
Code looks like this:
<?php
if(isset($_POST['next']))
{
displaynext();
}
else
{
global $image_folder = "/images/";
echo "global declared";
global $selection;
$selection = 1;
}
function displaynext()
{
$selection++;
if (file_exists($image_folder."/".$selection.".png")) {
echo "<img src=\"$image_folder/".$selection.".png\">";
}
else {
echo "No next image was found for $selection in ".$image_folder."/".$selection.".png";
}
?>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<input type="submit" name="next" value="Next">
</form>
Once PHP runs and the output is sent to the client, the code will not run unless the page is requested again from the server. You could create a session variable and use that to store the variable across page requests. You need to either access the page again or perform an AJAX request to call your PHP code again.
Instead of using Global, why don't you use a $_SESSION var?
Put:
global $selection
inside your function, so:
global $selection;
$selection++;
Just use another form element.
<input type=hidden name=selection value=1>
Do a sanity check like is_numeric on $_POST['selection'] before displaying the image tag. If $_POST['selection'] is set, increment it for the input tag above.
Full example:
<?php
$selection = 0;
$image_folder = "images/";
if (isset($_POST['selection'])) {
$userSelection = $_POST['selection'];
if (is_numeric($userSelection) && file_exists($image_folder . $userSelection)) $selection = $userSelection;
}
echo "<img src=\"images/" . $selection . ".png\">";
echo "<form action=\"" . $_SERVER['PHP_SELF'] . "\" method=post>";
echo "<input type=hidden name=selection value=\"" . ($selection + 1) . "\">";
echo "<input type=submit name=subnext value=\"Next\">";

Categories