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
Related
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.
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.
I use this snippet to get vehicle data from a external database:
<form method="post" action="<?php echo $_SERVER['REQUEST_URI'] ?>" class="vwe-kenteken-widget">
<p><input type="text" name="open_data_rdw_kenteken" value="<?php echo $_POST['open_data_rdw_kenteken'] ?>" maxlength="8"></p>
<p><input name="submit" type="submit" id="submit" value="<?php _e('Kenteken opzoeken', 'open_data_rdw') ?>"></p>
</form>
<?php if($data): ?>
<h3><?php _e('Voertuiggegevens', 'open_data_rdw') ?></h3>
<table>
<?php
$categories = array();
foreach ($data as $d) {
if( !is_array($fields) || in_array($d['name'], $fields) ) {
if( !in_array($d['category'], $categories) ) {
$categories[] = $d['category'];
echo '<tr class="open-rdw-header">';
echo '<td colspan="2" style="font-weight: bold;">';
echo ''.$d['category'].'';
echo '</td>';
echo '</tr>';
}
echo '<tr style="display:none">';
echo '<td>'.$d['label'].'</td>';
echo '<td>'.$d['value'].'</td>';
echo '</tr>';
}
}
?>
</table>
<?php endif; ?>
What i want to accomplish is that the data is loaded without the user have to enter a value and hit the submit button. The input value will get loaded based on the product page the user is viewing.
EDIT:
The data is loaded based on:
public function get_json() {
if ( isset( $_POST['kenteken'] ) ) {
$data = $this->rdw->get_formatted($_POST['kenteken']);
foreach ($data as $row) {
$json['result'][$row['name']] = $row['value'];
}
if ($_POST['kenteken']) {
if ($data[0]['value'] == '') {
$json['errors'] = __( 'No license plates found', 'open_data_rdw' );
}
else {
$json['errors'] = false;
}
}
else {
$json['errors'] = __( 'No license plate entered', 'open_data_rdw' );
}
header('Content-type: application/json');
echo json_encode($json);
die();
}
}
So instead of a $_POST action just get the data based on a pre-declared value that is different on each page.
Hard to answer - but I'll try to use my crystal ball.
$data comes from a database query, right?
I assume further, that the query takes the value from the open_data_rdw_kenteken form field to gather $data.
To have the table rendered, you have to fill $data with the right data. That implies that you must have a kind of default value for open_data_rdw_kenteken to get the data out of the DB. The default can be "all" which should reflect on your SQL Query or as your wrote "defined by product page".
Pseudo Code
$data = getData('BT-VP-41');
function getData($open_data_rdw_kenteken="")
{
$where = "";
if(!empty($open_data_rdw_kenteken)) {
$where = 'WHERE rdw_kenteken = "'.mysqli_real_escape_string($open_data_rdw_kenteken)';
}
$data = myslqi->query("SELECT * FROM dbTbl ".$where)
return $data;
}
As I wrote - this is pseudo code and will not run out of the box. You'll have to adapt that to your environment.
TL;DR: The line
<?php if($data): ?>
keeps you from rendering the table. To render you need $data filled with the right data.
Hope that will get you in the right direction.
i have an array of classes in a php file, this class has 3 fields, and i am using these fields to save the values of SELECTS and INPUT CHECKBOXs inside a FORM using POST, then i need to send this array of classes to another php file for proccessing data.
<?php
class info_subject{
public $code_as;
public $time_as;
public $selectionn_as;
}
$subjects[0] = new info_subject();//The only way I have seen for creating an array of classes
//is with a for loop, but if you have a better way for doing this, please let me know
$subjects[1] = new info_subject();
//here i am using the fields to save info in a form
$i=0;
echo "<form name = 'formsubjects' method='post' action='file2.php'>";
echo "<select name=\"".$subjects[$i]->time_as ."\">";
//options
echo "</select>";
echo "<input type='checkbox' name=\"".$asignaturas[$i]->selection_as."\">";
//and so on with every position of the array using $i
?>
//then there is a button to send the the dato to file2.php
//file2.php
<?php
$subjects=$_POST["$subjects"];//I am using this but i cant retrieve the fields of $subjects
?>
What can i do buddies?
instead of:
$i=0;
echo "<form name = 'formsubjects' method='post' action='file2.php'>";
echo "<select name=\"".$subjects[$i]->time_as ."\">";
//options
echo "</select>";
echo "<input type='checkbox' name=\"".$asignaturas[$i]->selection_as."\">";
you can try something like:
$i=0;
echo "<form name = 'formsubjects' method='post' action='file2.php'>";
echo "<select name=\"subjects[$i][".$subjects[$i]->time_as ."]\">";
//options
echo "</select>";
echo "<input type='checkbox' name=\"subjects[$i][".$asignaturas[$i]->selection_as."]\">";
and then in file2
$subjects=$_POST["subjects"];
and pick off what you need.
To be honest, I find your question hard to understand. Maybe try streamlining your problem and clean up some code/formatting and it will be easier for us to give you advice.
You can't submit a class or array via $_POST because the post array is an array which can only contain simple values.
Hi~ Jose Ricardo Citerio. I hope you can read Chinese
我不知道你是不是需要这样,在file1里面存储着select的option选项。然后file2接收去后处理
<?php
class info_subject{
public $code_as = ['name' => 'select_name', 'option' => ["k" => "v"]];
public $time_as;
public $selectionn_as;
}
$subjects = new info_subject();
echo "";
echo 'code_as["name"] . '">"';
//loop options for $subjects["option"] and print k and v; like => foreach($subjects->code_as["name"] as $k => $v){echo '' . $v . '';}
echo "";
echo 'xxx['name'] . '">please check';
?>
//then there is a button to send the the dato to file2.php
//file2.php
<?php
$subjects = $_POST["select_name"];
$subjects1 = $_POST["checkbox_name"];
?>
I am developing a wordpress plugin , which submits a form to another page. But when I try to submit the form to another page , then that page returns some php error. My form code is below
echo "<form action='".plugins_url()."/wp_voting_poll/frontend_poll_process.php' method='post'>";
echo "<input type='hidden' name='hide' value='$ques' />";
$total_vote_count = $wpdb->get_var( "SELECT COUNT(*) FROM $table_result WHERE question_uid='$ques'" );
if($ques!=""){
echo "<table>";
foreach($ans_data as $ans_res){
// $ans=$ans_res->answer;
$answer_id=$ans_res->id;
$type=$ans_res->answer_type;
$vote_count = $wpdb->get_var( "SELECT COUNT(*) FROM $table_result WHERE answer_id='$answer_id'" );
if($vote_count==0){
error_reporting(0);
}
$vote_percent=($vote_count*100)/$total_vote_count;
echo "<tr> <td>";
echo "<div class='answer_div'>";
if($type==1){
echo "<div class='input'><input type='radio' name='ans_name[]' value='$answer_id'/>".$ans_res->answer."<br/></div>";
}
elseif($type==0){
echo "<div class='input'><input type='checkbox' name='ans_name[]' value='$answer_id'/>".$ans_res->answer."<br/></div>";
}
if($backend==0){
echo "</td> <td>";
echo "<h4> total vote counted $vote_percent% </h4>";
// echo "<img src='$url' width='$width_img'/>";
$bar=$vote_percent*5.9;
echo "<img src='$url' height='10' width='$bar' />";
echo "</td></tr>";
}
}
echo "</table>";
echo "<input type='submit' value='Submit vote' />";
echo "</form>";
And this is my code of another page , which should process the form . But unfortunately it returns php error.
<?php
require_once("function_ip.php");
$vote_result=$_POST['ans_name'];
$uid=uniqid();
global $wpdb;
$table_vote=$wpdb->prefix."poll_answer_result";
$count=count($vote_result);
$hidden=$_POST['hide'];
$ans_data=$wpdb->get_results("SELECT * FROM $table_vote WHERE question_id='$hidden'" );
if($count>0){
foreach($vote_result as $vote_arr){
$wpdb->insert($table_vote,
array('answer_id' => $vote_arr,
'ip' =>get_client_ip(),
'question_uid' => $hidden
));
}
}
?>
Wordpress has a generic handler to deal with all forms - admin-post.php.
If you include a hidden field in your form called action, you can then hook in to a function of your choice with all the goodness of wordpress included.
echo "<form action='".get_admin_url()."admin-post.php' method='post'>";
echo "<input type='hidden' name='action' value='submit-form' />";
echo "<input type='hidden' name='hide' value='$ques' />";
{ Enter the rest of your first block of code from above here }
echo "</form>";
And then in your functions.php file (or any other php file that you have included via functions.php), you can use this method.
add_action('admin_post_submit-form', '_handle_form_action'); // If the user is logged in
add_action('admin_post_nopriv_submit-form', '_handle_form_action'); // If the user in not logged in
function _handle_form_action(){
{ Enter your second block of code from above here }
}
I'm not sure if you require a redirect once you reach your desired destination, but that can be easily accounted for if you do.
And one final question - is this form on the front end, or in the admin area? Not that it should make a difference that this answer, I'm just curious...
Your frontend_poll_process.php page is getting called out of the WordPress environment, therefore returning an error on $wpdb->get_results().
You can add your code to a plugin or functions.php using hooks:
<?php
add_action( 'after_setup_theme', 'so_19997913' );
function so_19997913() {
require_once("function_ip.php");
$vote_result = $_POST['ans_name'];
$uid = uniqid();
global $wpdb;
$table_vote = $wpdb->prefix . "poll_answer_result";
$count = count( $vote_result );
$hidden = $_POST['hide'];
$ans_data = $wpdb->get_results( "SELECT * FROM $table_vote WHERE question_id='$hidden'" );
if ( $count > 0 ) {
foreach ( $vote_result as $vote_arr ) {
$wpdb->insert( $table_vote, array('answer_id' => $vote_arr,
'ip' => get_client_ip(),
'question_uid' => $hidden
) );
}
}
}