Avoid losing POST data when using php pagination - php

I am working on a renting website that transfer date from page to another, for example the user enter a date and some information and when he goes to another page he should find the information that he entered in the first page. Everything works fine except that when I add pagination like this: [1] [2] [3] [4] every time I click on a page number in the pagination the POST data will be lost. For example if I clicked number 2 in the pagination I get this message:
Undefined index: date......
I found some solutions which is using get method but I don't know how to use get method in this situation.
What should I change to my code to avoid losing POST data?
here is my full code:
<?php
$date= $_POST['date']; // the post data from previous page
$info= $_POST['info']; // the post data from previous page
?>
<form action="next_page.php" method="post" name="myForm">
<input name="date" type="hidden" value="<?php echo $date; ?>" />
<input name="info" type="hidden" value="<?php echo $info; ?>" />
<?php
include(db.php);
$q="select count(*) \"total\" from users";
$ros1=mysql_query($q,$link);
$row=(mysql_fetch_array($ros1));
$total=$row['total'];
$dis=8;
$total_page=ceil($total/$dis);
$page_cur=(isset($_GET['page']))?$_GET['page']:1;
$k=($page_cur-1)*$dis;
$query="SELECT * FROM cars limit $k,$dis";
$ros=mysql_query($query,$link);
while($row = mysql_fetch_array($ros))
{
echo $row["user_id"];
echo $row["user_name"];
echo $row["user_email"];
}
for($i=1;$i<=$total_page;$i++){
if($page_cur==$i){
echo ' <input type="button" value="'.$i.'"> ';
}
else{
echo ' <input type="button" value="'.$i.'"> ';
}}
?>
<input type="submit" name="userId" value="' .$row['user_id'] . '" />
</form>

You should use GET method instead of POST method.
<?php
$date = $_GET['date']; // the post data from previous page
$info = $_GET['info']; // the post data from previous page
?>
<form action="next_page.php" method="get" name="myForm">
<input name="date" type="hidden" value="<?php echo $date; ?>" />
<input name="info" type="hidden" value="<?php echo $info; ?>" />
<?php
include(db . php);
$q = "select count(*) \"total\" from users";
$ros1 = mysql_query($q, $link);
$row = (mysql_fetch_array($ros1));
$total = $row['total'];
$dis = 8;
$total_page = ceil($total / $dis);
$page_cur = (isset($_GET['page'])) ? $_GET['page'] : 1;
$k = ($page_cur - 1) * $dis;
$query = "SELECT * FROM cars limit $k,$dis";
$ros = mysql_query($query, $link);
while ($row = mysql_fetch_array($ros)) {
echo $row["user_id"];
echo $row["user_name"];
echo $row["user_email"];
}
for ($i = 1; $i <= $total_page; $i++) {
if ($page_cur == $i) {
echo ' <input type="button" value="' . $i . '"> ';
} else {
echo ' $i ';
}
}
?>
<input type="submit" name="userId" value="' .$row['user_id'] . '" />
</form>

You can use PHP sessions to store users input on the server:
PHP Sessions
Keep all the data in $_SESSION and read it from there when it's needed in the page.
Update the stored values when the users inputs something new.

You should store this information somewhere between your http-requests. There are some possible solutions for that:
you can store this information in the database
in session (temporarily store, if you don't need this data in your database)
store in every html page as a hidden field

A good way in my opinion is to start the seach with a POST form and if the results exceed a limit then construct pagination links which really are post forms incorporating the search keyword and target page in the form of hidden variables.
Passing the search keyword as a get parameter needs care (url encode) because urls have limits on the characters they allow (ascii letters and digits, and characters such as /, ~, -, _ etc ) for example a user might search for something in japanese or greek or use symbols.
Passing the search keyword as a session variable also needs care. Consider this scenario: a user has opened multiple result pages, but all pages will hereafter have access to the last processed session saved keyword. Also storing the search keyword in a session requires coordination by the developer such as when to destroy the session variable etc.

Related

Populate textbox with table entry plus one?

I am trying to increment project number based on the last entry. The the primary key PROJECTNOID auto-increments but is not the same format as the project number (Ex: PROJECTNOID = 1 and Project Number = 19000). I don't want this to be a dropdown box even though some of my code shows the opposite.
<?php
connect = mysqli_connect("**", "**", "**", "**");
$query4 = "SELECT PROJECTNOID, ProjectNumber FROM tblProjects ORDER BY
PROJECTNOID";
$result4 = mysqli_query($connect,$query4);
$options4 = "";
while($row4 = mysqli_fetch_row($result4);){
$options4 = $options4."<input value=$row4[0]$row4[1]</input>";
}
?>
Here is the html textbox:
<label for="txtfield">Project Number</label>
<!--<input type="text" id="reqtxtfield" name="projectnumber"
value="<?php ?>" readonly/>-->
<?php echo $options4;?>
But it would look like how you had it but instead of '1' inside the
box it would display '19000' and there would be nothing outside of the
box other than the label "Project Number". As far as i'm aware you can
assign a value to the text box, regardless of whatever the input is. I
would like it to display the value from one field name but actually
contain the value from a different field name. Both are in the same
table of course.
OK - gotcha. Unfortunately, you cannot do that. A textbox can only have one value and the user is always free to change that value, even if you make it read-only. You can test that out by using the developer toolbar in your browser. Probably a good time to mention that all user input should be considered dangerous and you should never trust it. Once they have submitted the form you need to verify it.
What I would recommend in your case is to use a hidden <input> which contains the value you actually want to submit; projectnoid. You can then display the Project Number in any manner you choose.
<form>
<h1>Project Number: 19000</h1>
<input type="hidden" name="projectnoid" value="1">
<input type="submit" name="submit">
</form>
To generate this, you would:
<?php
while($row4 = mysqli_fetch_row($result4)){
$projectnoid = $row[0];
$projectNumber = $row[1];
echo '<h1>' . $projectNumber . '</h1>';
echo '<input type="hidden" name="projectnoid" value="'. $projectnoid .'">
}
PHP:
<?php
$query_5 = "SELECT MAX(ProjectNumber) FROM tblProjects;";
$result_5 = mysqli_query($conn, $query_5);
$row_5 = mysqli_fetch_array($result_5);
$nextproject=$row_5['MAX(ProjectNumber)']+1;
?>
HTML:
<html>
<form class="myform" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>" method="post">
<label for="txtfield">Project Number</label>
<input type="text" id="reqtxtfield" name="projectnumber" value="<?php echo $nextproject ?>" readonly/><br>
After running successful insert query:
echo "<meta http-equiv='refresh' content='0'>"; //REFRESH PAGE TO UPDATE PROJECT NUMBER

echo a function value won't pass on a form

----UPDATE: trying to find a different solution here, please take a look -------
I am trying to post a form with hidden values on a shop platform with payment gateway to receive the values.
The value name "Order_Total" uses php echo called "$sum" to display the sum to pay like this:
<Input type="hidden" name="sum" value="<?php echo $order_total; ?>">
$sum is a function which reads the user order id amount
$order_total = left_to_pay_for_order($oid);
the function works like this:
function left_to_pay_for_order($oid)
{
global $wpdb;
$s = "select * from ".$wpdb->prefix."order_contents where orderid='$oid' and paid='0'";
$r = $wpdb->get_results($s);
$total = 0;
if(count($r) > 0)
{
foreach ($r as $row)
{
$total += $row->price * $row->quant;
$shp = get_post_meta($row->pid, 'shipping', true)* $row->quant;
$total += $shp;
}
}
return $total;
}
The Payment gateway receives all other values except the $order_total value.
UPDATE !!! --------------------------------
The value passed as '0' - Any thoughts on that can happen ?
I have tested and the function works prior to sending the form and redirect, the sum display according to expected result on any HTML prior to sending, but the form send value "0".
what am I doing wrong? have searched everywhere. your kind help is very much appreciated.
Thanks !!
As per request here is the whole Form page Code - modified per StackOverflow:
<?php
global $wp_query, $wpdb, $current_user;
get_currentuserinfo();
$uid = $current_user->ID;
$user_email = $current_user->user_email;
$business = get_option('Theme_tranzilla_ID');
if(empty($business)) die('ERROR. Please input your tranzilla ID.');
//-------------------------------------------------------------------------
$oid = $_GET['oid'];
$order_total = Theme_left_to_pay_for_order($oid);
$title_post = sprintf(__('Order Payment ID #: %s','Walleto'), $oid);
//---------------------------------
$tm = current_time('timestamp',0);
$cancel_url = get_bloginfo("siteurl");
$response_url = get_bloginfo('siteurl').'/?w_action=tranzila_order_response';
$ccnt_url = Theme_my_account_link();
$currency = get_option('Theme_currency');
?>
<html>
<head><title>Processing Tranzilla Payment...</title></head>
<body onLoad="document.form_mb.submit();">
<center><h3><?php _e('Please wait, your order is being processed...', 'Theme'); ?></h3></center>
<FORM name="form_mb" Action='https://direct.tranzila.com/Terminal_Name/' method='POST'>
<Input type="hidden" name="supplier" value="<?php echo get_option('Theme_tranzilla_ID') ?>">
<Input type="hidden" name="sum" value="<?php echo $order_total; ?>">
<Input type="hidden" name="currency" value="1">
<input type="hidden" name="email" value="<?php echo $user_email; ?>">
</FORM>
</body>
</html>
Please, tell us what you see in a "inspect".. what the value in the input before post.
But.. with information that you give, I think:
1) You are missing a ; in the end of "echo $order_total" line. Put a ; in the end.
2) It can be some wordpress conflict with the "sum" field name. Try to change to "order_total".

Using a PHP variable as a form fields default value

I have a created an HTML form where users sign up and input there data into an SQL database. I have then retrieved that data in a webpage where they can view their profile. I have created a page where users can edit there profile by creating a form which updates the value in the SQL database for there user id.
I would like the form to use the current value of the SQL cell as the default for that user to make alterations easier. Example: currently user 7 has their city set as New York, when they visits the edit info page, the city field in the form already hase New York as the default value.
I have no problem getting the SQL info and assigning it to a variable, I just don't understand how to set it as the default value. I am aware of how you set default values for input fields though.
My code:
<?php
$id = $_SESSION["user_id"];
// Create a query for the database
$query = "SELECT full_name FROM users WHERE id = $id LIMIT 1";
// Get a response from the database by sending the connection
// and the query
$response = #mysqli_query($dbc, $query);
// If the query executed properly proceed
if($response){
while($row = mysqli_fetch_array($response)){
echo $row['full_name'];
echo mysqli_error();
}
}
?>
<input type="text" name="aboutme" defualt="<?php echo $row['aboutme'] ?>" >
There's no default value for html input.
Input can has value, using attribute value:
<input type="text" name="some_name" value="Some value" />
In your case it's
<input type="text" name="aboutme" value="<?php echo $row['aboutme']?> />
Input can also has placeholder - some value that is present in an input, but erased when user starts to edit input's content:
<input type="text" name="aboutme" value="<?php echo $row['aboutme']?> placeholder="some value" />
How about
<?php
$id = $_SESSION["user_id"];
// Create a query for the database
$query = "SELECT full_name FROM users WHERE id = $id LIMIT 1";
// Get a response from the database by sending the connection
// and the query
$response = #mysqli_query($dbc, $query);
// If the query executed properly proceed
if($response){
while($row = mysqli_fetch_array($response)){
echo $row['full_name'];
?>
<input type="text" name="aboutme" value="<?php echo $row['aboutme'] ?>" >
<?php
echo mysqli_error();
}
}
?>
And here is a good example http://www.w3schools.com/php/showphpfile.asp?filename=demo_db_select_pdo
Neither of the answers worked and upon further research and trial and error I created a solution.
I changed the value that was store in the array to just be a normal php variable:
$aboutme = $row['aboutme'];
I then called that variable using the following code:
<input type="text" name="aboutme" value="<?php echo htmlspecialchars($aboutme); ?>" >
Thanks for your help.
I hope you find my answer useful.
Why don't you try using it as a place holder? This will provide editable text.
<input type="text" name="aboutme" placeholder="<?php echo $row['aboutme'];" />

pre-populating a form field after choosing between many options using a radio button

I have searched across the entire web and I cant seem to find a solution. I am pretty much searching a database for individuals. I can use last name for instance and then if two people have the same last name they both will print on my page. I want to be able to select the individual I would want ( or am for instance ) and click next ( a hyperlink to a page with blank forms ) which is where I would like the info of the individual I selected ( and what was printed on the page ) in the forms pre filled. It allows a more user friendly approach then having to re type the data and also avoid miss spelling of company name or drivers license for example. I have put my code up many times but here it is again.this is the code for the finding and printing of the search results. no radio button yet, as i am trying to figure that out.
<div id="results" style="width:750px;height:225px; text-align: center">
<?php
$host = "localhost"; //server
$db = ""; //database name
$user = ""; //databases user name
$pwd = ""; //password
mysql_connect($host, $user, $pwd) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
$searchTerm = trim($_GET['searchname']);
// Check if $searchTerm is empty
if($searchTerm == "")
{
echo "Enter name you are searching for.";
exit();
}
else
{
//$sql = "SELECT * FROM contractor WHERE CONCAT(FIRSTNAME,' ',LASTNAME,' ',
ARRIVAL) like '%$searchTerm%' GROUP BY FIRSTNAME";
$sql= "SELECT * FROM contractor WHERE CONCAT(FIRSTNAME,' ',LASTNAME,' ', ARRIVAL)
like '%$searchTerm%'";
$query = mysql_query($sql);
$count=mysql_num_rows($query);
//array_unique($count);
if(($count)>=1)
{
$output = "";
while($row = mysql_fetch_array($query))
{
$output .= "First Name: " . $row['FIRSTNAME'] . "<br />";
$output .= "Last Name: " . $row['LASTNAME'] . "<br />";
$output .= "Arrival: " . $row['ARRIVAL'] . "<br />";
}
echo $output;
//echo array_unique($output);
}
else
echo "There was no matching record for the name " . $searchTerm;
}
?>
</div>
this is the code for my form field which of course is a empty form that is just being submitted to the database after submission.
<form action="insert_submit.php" method="post" style="margin-left:35px;">
First Name: <input type = "text" name="FIRSTNAME" id="FIRSTNAME" />
Last Name: <input type = "text" name="LASTNAME" id="LASTNAME"/>
Purpose: <input type = "text" name="PURPOSE" id="PURPOSE"/>
<br>
</br>
Company: <input type = "text" name="COMPANY" id="COMPANY" />
DL #: <input type = "text" name="DRIVERL" id="DRIVERL" />
<br>
</br>
<input type="radio" name="STATUS" id="STATUS" value="Checked In">Log In
<br></br>
<input type="radio" name="STATUS" id="STATUS" value="Checked Out">Log Out
<br></br>
<input type="submit" value="Submit" >
<br>
</br>
</form>
so your output line would be something like (clean up to suit your formatting)
$output .= '<a href="'.$_SERVER['PHP_SELF'].'?userid='.$row['UNIQUEID'].'">
First Name: '.$row['FIRSTNAME'].'<br />
Last Name: '.$row['LASTNAME'].'<br />
Arrival: '.$row['ARRIVAL'].</a><br />';
and you build into the page a condition that if you have the UNIQUEID coming in to look up and fill out the form such as
Company: <input type = "text" name="COMPANY" id="COMPANY" value="<?PHP echo $row['COMPANY']; ?>" />
edit to suit your database of course
sample code formatting
if(something){
do something
}else{
while(){
} # end while
} # easy to see this matches the if/else set of brackets
additional information for prepopulating
easiest would probably be on the same page. look for the userid coming into the page
if(!isset($_GET['userid'])){
# meaning we do not have a userid from a url that we generated above
# insert all your code to generate the links
}else{
# meaning we *have* a userid from a url that we generated above
# do your database query based on the userid such as
$sql='select * from mytable where userid=?';
$result=sqlsrv_query($db,$sql,array($_GET['userid']),array('Scrollable'=>'static'));
# or use mysqli, pdo or whatever... just watch for sql injection
$row=sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC));
# assuming we will not have more than one element returned
?>
First Name: <input type = "text" name="FIRSTNAME" id="FIRSTNAME" value="<?PHP echo $row['firstName']; ?>"/>
and so forth... that should get you started
So basically what you need is in the first page a lis of identical names, or ideally one name, like:
content, content, content,
FirstName, LastName
FirstName, LastName
And than if you click on either of them, than the user is redirected to another page, containing all the details of the selected person, in a form. If I am getting you right.
I would not use checkbos on the first page, simply make the person's name a hyperlink like:
http://domain.com/userdetails?userid=666
So you pass on the user id to the second page. The php code on the second page can thank draw user details from the database and populate the form.
For that purpose you can either generate the form in an echo line-by-line manner, or use DomDocument tofind and fill the relevant value fields.
Second page form generation:
you select the row with the id, than fetch it into an array, named $array.
$array = mysql_fetch_array($query); //this query selected the row for the user with the id
echo '<form method="POST">'."\n";
echo '<input name="firstname" type="text" value="'.$array['firstname'].'">'."\n";
echo '<input name="lastname" type="text" value="'.$array['lastname'].'">'."\n";
echo '</form>';
I hope you get the idea now.

Inputting multiple values in database from HTML form using PHP

I'm trying to add multiple values into a database using PHP from an HTML. However, I can't just refer to the name attribute of the HTML form because each field in the form is generated by a PHP script. I've tried Googling around, but since I don't exactly know what I'm looking for, my search has been futile.
Here's the bit of code that I use to generate the HTML form:
<form action="input_points.php" method="post">
<?php
while($row = mysql_fetch_array($result)) {
echo $row['Name'] . ' <input type="text" name="userpoints">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
I don't know what names are currently in the directory so I need this piece of php to determine what names are in the database. Afterwards, I want to have a bunch of boxes for people to input points (hence the form). I'm having trouble figuring out how to link the particular text box with the user.
For example, if I have a text box for Bob, how would I link up the input text field that contains the number of points Bob earns with Bob's entry in the database?
I know you can do this with regular form fields:
$userpoints = $_POST['userpoints'];
UPDATE members SET points = $userpoints where $user = "Bob";
But since I have multiple users, how do I link up the correct database entry with the right user? Also, how would I determine which boxes are empty and which boxes are updated with a value?
If you want to update multiple filed then are using array
Please changes some code
<form action="input_points.php" method="post">
<?php
$userCount=mysql_num_rows($result);
echo '<input type="hidden" name="userCount" value="' .$userCount. '">';
while($row = mysql_fetch_array($result)) {
echo '<input type="hidden" name="userid[]" value="' .$row['id']. '">'; //Give the uniq id
echo $row['Name'] . ' <input type="text" name="userpoints[]">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
PHP Code -
$userCount = $_POST['userCount'];
for($i=1; $i=$userCount; $i++){
$userpoints = $_POST['userpoints'];
$userid = $_POST['userid'];
//UPDATE members SET points = $userpoints where $user = $userid;
//YOUR CODE HERE
}
The update you're trying to do is not safe unless you treat values to prevent SQL injection... but if you really want it, instead of mysql_fetch_array(), try using mysql_fetch_assoc().
Using mysql_fetch_assoc() you can extract the keys (database field names) with array_keys(). The keys will be your the name property of your form fields and the values of will be the fields' values.
Hope it helps.
You can use an array to store all the data that you need and add a hidden field that contains the missing data:
<form action="input_points.php" method="post">
<?php
for($i=0; $row = mysql_fetch_array($result); $i++ ) {
echo ' <input type="hidden" name="user[0]['name'] value ='". $row['name'] ."'">';
echo $row['Name'] . ' <input type="text" name="user[$i]['points'] ">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
Problem when you hit submit userpoints contain only the last value previous all values are overwritten
solution
name="userpoints"
must be different each time why not you define it in database and then fetch it just like you fetch $row['Name']?

Categories