I am currently working on a form that requires few fields to be filled by the user and few based on the selection made by the user on the previous page. The URL looks like below:
http://localhost:8080/series/dynamics/admin/cleanURL/post.php?subgroup=redapple&adverid=254427035
where redapple is the $_GET variable. However what I wd like the url to look like is ;
http://localhost:8080/series/dynamics/admin/cleanURL/post.php?adverid=254427035
i.e. no info about subgroup selection in the url. But still would like to have the subgroup field to be filled with the choice made by user.
My php looks like this:
<?php require('../config/connection.php');
if(isset($_POST['variable'])){
$values = mysqli_real_escape_string($dbc, $_POST['variable']);
$query = "SELECT * FROM prdct_categories WHERE product = '$values'";
$result = mysqli_query($dbc, $query);
$rand = rand(0, 1000000);
$html = '<ul>';
while($row = mysqli_fetch_assoc($result)){
$clickable_url = 'post.php?subgroup='.$row['subgroup'].'&advertid='.$rand;
$html .= '<li class="nav">';
$html .= ''.$row['subgroup'].'';
$html .= '</li>';
}
$html .='<ul/>';
echo $html;
mysqli_close($dbc);
}
If you don't want to pass information in the URLs then you'll need to use a Cookie or Session. Post the form to a page that gathers the posted data and then set a session or cookie before redirecting the user to the correct page.
http://php.net/manual/en/features.cookies.php
Or
http://php.net/manual/en/features.sessions.php
You can also use a POST request, for example, if I made a form like:
<form action="form_url.php" method="get">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
In form_url.php, I could access the variables like so:
<?php
var_dump($_POST);
The benefit of using POST over GET is that in can be encrypted over SSL whereas all parameters inside a GET request are encoded and visible in the URL. Also, since the URL can only be 265 characters max, that's also the limit of the data size.
If you want to upload something such as an image, you'll want to use a file input in a form field (like the one above) so that data can be sent over a file-stream instead of a url.
EDIT:
If you want another way to just get the url data, you don't have to use get. The full URL can be given by:
<?php
var_dump($_SERVER['HTTP_HOST']);
var_dump($_SERVER['REQUEST_URI']);
Although the REQUEST_URI is probably what you want. Note that any data passed through here can also be obtained from GET, but you don't have to use GET to get the data. You would then want to parse the URL with something like:
<?php
var_dump(explode('\', $_SERVER['REQUEST_URI']));
Related
Good morning everyone,
I have a page that performs a default connection to database, search and looped output of data to the page by applying a template for each result in the table using this code:
<?php
$result = mysqli_query($con,"SELECT * FROM XXX WHERE Type='ABCD';");
while($row = mysqli_fetch_array($result))
{
include('includes/template-1234.php');
}
mysqli_close($con);
?>
On the same page I have a simple HTML search box:
<div id="srch-form">
<form>
<input name="srch-box" type="text" id="srch-box" size="45" onClick="this.value='';" onFocus="this.select()" onBlur="this.value=!this.value?'Enter Product Name or SKU#':this.value;" value="Enter Product Name or SKU#">
<input type="submit" name="srch-btn" id="srch-btn" value="Search">
</form>
</div>
Because I am just learning PHP - how do I set this up so that the default action still occurs on page entry, but - onsubmit of something in the searchbox the data in the current page is replaced by the results of the submission? I guess I'm getting confused over the fact that since I have already assigned a value(s) to $result to get the default output, If the value of $result is changed by the search form, does PHP automatically refresh the page when the value of $result is changed? - Sorry if this is a simple thing.
First, you'll have to add an action (which file to refer when submitted) and preferably a method-type in your form-tag. You will also have to include value of $productName (given from server-side php) inside of your html (look at value attribute)
Do something like this:
html-form: (Examplefile: yourhtmlform.php)
Then in your php-file get value from a specific element like this:
<?php
//File querydb.php (example filename)
//Form is submitted and srch-box is set (only set when form is submitted)
if(isset($_POST['srch-box'])) {
$type = $_POST['srch-box']; //Get value of input-element
}
else {
$type = 'kingkong'; //Default type to search
}
$prepareQuery = mysqli_prepare($dbConnectionLink,"SELECT * FROM XXX WHERE Type=:type");
//...code to fetch results..
//You get a productName (or SKU) from db
if (isset($result['product_name'])) {
$productName = $result['product_name']; //or whatever your column is called
}
else {
$productName = '';
}
include('yourhtmlform.php'); //Observe that it must be php to echo out value of $productName in this included file
I noticed you didn't use prepared-statement. Look for more information on prepared statements here: http://www.php.net/manual/en/mysqli.prepare.php (use them!)
I hope this will help you somehow :-)
I am trying to setup a website that converts a Steam user ID into an auth ID. It will ask for the visitor to input their regular Steam ID and then hit a button to convert it to auth ID. Steam provides us with the function for ID conversion from one type to the other.
Steam function for converting IDs:
function convert_steamid_to_accountid($steamid)
{
$toks = explode(":", $steamid);
$odd = (int)$toks[1];
$halfAID = (int)$toks[2];
$authid = ($halfAID*2) + $odd;
echo $authid;
}
Below is my attempt at setting up a basic HTML page that gets user input and then uses the function to convert that input to something else.
<INPUT TYPE = "Text" VALUE ="ENTER STEAM:ID" NAME = "idform">
<?PHP
$_POST['idform'];
$steamid = $_POST['idform'];
?>
Also, this is what the default Steam user ID looks like:
STEAM_0:1:36716545
Thank you for all the help!
If you can make it into two seperate files, then do so.
foo.html
<form method="POST" action="foo.php">
<input type="text" value="ENTER STEAM:ID" name="idform" />
<input type="submit" />
</form>
foo.php
<?php
function convert_steamid_to_accountid($steamid)
{
$toks = explode(":", $steamid);
$odd = (int)$toks[1];
$halfAID = (int)$toks[2];
$authid = ($halfAID*2) + $odd;
echo $authid;
}
$id = $_POST['idform'];
convert_steamid_to_accountid($id)
?>
if you don't have an option of making two seperate files, you can add the php code to 'foo.html' file and make the form to submit to the same file. However if you do this, check if the file is getting requested the first time, or it is requested because the form is submitted, BEFORE you call convert_steamid_to_accountid() function.
You can do this by:
if ($_SERVER['REQUEST_METHOD']=='POST'){
// your php code here that should be executed when the form is submitted.
}
I'm trying to "pre-fill" (not sure if there's a technical term for this) form fields with values that the user has previously entered in the database. For this example it's a City and State. When the user loads the page to edit options, these values (which they have previously entered) will automatically be in the text boxes.
<tr><td>City</td><td><input type="text" name="city" value="<? $city = "usercity"; echo $formValue->location('$city'); ?>"></td>
<td>State</td><td><input type="text" name="state" value="<? $state = "userstate"; echo $formValue->location('$state'); ?>"></td>
Is there any way to set a value based on the input (from the boxes above)? If it was something like function location($input) I would know how to, but when there's nothing in the parenthesis, is there any way to set a value?
function location(){
$userid = $_SESSION['userid'];
$server = 'localhost';
$user = 'root';
$password = '';
$connection = mysql_connect($server, $user, $password) or die(mysql_error());
mysql_select_db(testdb, $connection) or die(mysql_error());
$result = mysql_query("SELECT '$location' FROM userinfo WHERE userid = '$userid'");
$user_data = mysql_fetch_array($result);
if($location =='usercity'){
$userlocation = $user_data['usercity'];
return $userlocation;
}
else
$userlocation = $user_data['userstate'];
return $userlocation;
}
Instead of thinking about this from a global perspective think about the problem in it's context.
Your starting point (from the server perspective) is that an HTTP GET request has come in from a client for this page, or a client is returning to this page from after a POST request. In either case, the server has located the "resource" (the PHP script) that should handle this request and dispatched it by loading the PHP interpreter with the script file.
The context at this point is at the first line of the script; at the point where the interpreter has just finished parsing and started executing. Ask yourself: does the current request include an active session identifier? If it does have an active session, then check to see if the client has filled in this form before and if they have, substitute the default form values they've previously submitted for the normal form default values. If the client does not have an active session or has not used the form before then show a blank form with default values as needed.
Tip: Consider using this technique to debug your code. Pick a line in your code and place a mental "break point" at that place. Ask yourself: what is the context of this script at this point? What variables are defined? What is the server state? What is the client expecting? Once you have an answer to those questions, writing the code is simple.
From what I see in your code you have the variable in single quotes:
$city = "usercity"; echo $formValue->location('$city');
remove the single quotes, as it will pass '$city' as is, not the value of $city. Try
$city = "usercity"; echo $formValue->location($city);
to make it clearer:
$city = "usercity";
print ('$city'); // will print $city
print ($city); // will print usercity
My last few projects had forms all over the place and telling php to fill out the forms each time was a pain in the arse.
For my current project, I kept the input names the same as the mysql field names. Makes submitting and populating way easier.
When it comes to populating the forms, I use some ajax (jQuery used all over the project so using jquery's ajax() function;
FORM
<form>
<input name="field_one" type = "text" >
<input name="field_two" type = "text" >
<input type="button" value="Send">
</form>
I put a conditional statement at the top of the doc along the lines of:
<?php if($_POST['update']){
$query=mysql_query("SELECT * FROM table WHERE unique_id='$id' LIMIT 1");
echo json_encode(mysql_fetch_assoc($query));
exit;
} ?>
Lets say you have a list of items you want to be able to click on and edit (populate the form with it's corresponding data). I assign it a data- attribute and fill it with it's unique id, normally an AI PRIMARYKEY eg:
while($r=mysql_fetch_assoc($data)){
echo "<li data-unique_id=\"\">$r[name]<span class="edit">edit</span></li>";
?>
$('.edit').click(function(){
var toget = $(this).parent().data('unique_id');
$.ajax({
url:'here so it sends to itself',
data:'update='+toget,
success:function(data){
for (var key in data) {
if (data.hasOwnProperty(key)) {
$('input[name="'+key+'"]').each(function(){
$(this).val(data[key]);
});
}
}
}
});
There's a little more work required for <select>, <textarea>, checkboxes, but same general idea applies, (I threw in a couple of if statements, but it could probably be handled way better)
I could probably explain this better, but I hope you get the idea and i've been of some help.
FYI
my inserts are like...
foreach($_POST as $k=>$v){
$v=mysql_real_escape_string($v);
$fields.=" `$k`,";
$vals.=" '$v',";
}
$fields=substr($fields,0,strlen($fields)-1);//to get rid of the comma :)
$vals=substr($vals,0,strlen($vals)-1);//and again
mysql_query("INSERT INTO ($fields) VALUES ($vals)");
header('Location: ' . $uri);
This will miss all the $_POST information.
Don't use $_SESSION as you have been suggested. Session data is shared with all other pages, including the ones open in other tabs. You may get unpredictable behaviour if you use the same trick in multiple places of your website.
An untested better code would be something like this.
session_start();
$data_id = md5( time().microtime().rand(0,100) );
$_SESSION["POSTDATA_$data_id"] = $_POST;
header('Location: ' . $uri."?data_id=$data_id");
In the next page you may retrieve the previous post like this
session_start();
$post = array();
$data_key = 'POSTDATA_'.$_GET['data_id'];
if ( !empty ( $_GET['data_id'] ) && !empty( $_SESSION[$data_key] ))
{
$post = $_SESSION[$data_key];
unset ( $_SESSION[$data_key] );
}
The code above is not tested, you may have to deal with some error before it works.
if u want to carry forward your POST data to another pages ( except the action page) then use
session_start();
$_SESSION['post_data'] = $_POST;
Indeed, you can't redirect POST requests.
Either let your server proxy the request (i.e. make a cURL request to the other site) or create another form, fill it with hidden fields and submit it with Javascript/let the user click.
Alternatively, as #diEcho says, depending on what you're trying to do: sessions.
If you perform a redirect the post will be lost and a GET will occur.
You could save your POST in a SESSION or encode it in the GET (as query string)
You could save the post data in the session, redirect, and then retrieve it back from the session.
session_start();
$_SESSION['POSTDATA'] = $_POST;
header('Location: ' . $uri);
Then in the PHP file for the new location, retrieve the post data like this:
$_POST = $_SESSION['POSTDATA'];
I do use my own simple method.
Just think very logical! For example if you use a text attribute which you want to keep the value of, you can use:
<?php $textvalue = $_POST['textname']; ?>
<input type="text" name="textname" value="<?php echo $textvalue; ?>" />
<br />
//And if you want to use this method for a radio button, you can use:
<?php if(isset($_POST['radio1']){
$selected = "selected";
} ?>
<input type="radio" name="radio1" <?php echo $selected; ?> />
ok, i'm trying to do a quiz...all good by now. but when i'm trying to send the collected data(radio buttons values) through pages i can't get the logic flow. I have the main idea but i can;t put it into practice.
i want to collect all radio values
create an array containing this values
serialize the array
put the serialized array into a hidden input
the problem is that i want to send data on the same page via $_SERVER['PHP_SELF'] and i don;t know when in time to do those things.(cause on "first" page of the quiz i have nothing to receive, then on the "next" page i receive the S_POST['radio_names'] and just after the second page i can get that hidden input). i hope i made myself understood (it's hard even for me to understand what my question is :D )
You could try to use the $_SESSION object instead... For each page of your quiz, store up the results in the $_SESSION array. On the summary page, use this to show your results.
To accomplish this, on the beginning of each page, you could put something like:
<?
session_start();
foreach ($_POST as $name => $resp) {
$_SESSION['responses'][name] = $resp;
}
?>
Then, on the last page, you can loop through all results:
<?
session_start();
foreach ($_SESSION['responses'] as $name => $resp) {
// validate response ($resp) for input ($name)
}
?>
Name your form fields like this:
<input type="radio" name="quiz[page1][question1]" value="something"/>
...
<input type="hidden" name="quizdata" value="<?PHP serialize($quizdata); ?>"/>
Then when you process:
<?PHP
//if hidden field was passed, grab it.
if (! empty($_POST['quizdata'])){
$quizdata = unserialize($_POST['quizdata']);
}
// if $quizdata isn't an array, initialize it.
if (! is_array($quizdata)){
$quizdata = array();
}
// if there's new question data in post, merge it into quizdata
if (! empty($_POST)){
$quizdata = array_merge($quizdata,$_POST['quiz']);
}
//then output your html fields (as seen above)
As another approach, you could add a field to each "page" and track where you are. Then, in the handler at the top of the page, you would know what input is valid:
<?
if (isset($_POST['page'])) {
$last_page = $_POST['page'];
$current_page = $last_page + 1;
process_page_data($last_page);
} else {
$current_page = 1;
}
?>
... later on the page ...
<? display_page_data($current_page); ?>
<input type="hidden" name="page" value="<?= $current_page ?>" />
In this example, process_page_data($page) would handle reading all the input data necessary for the given page number and display_page_data($page) would show the user the valid questions for the given page number.
You could expand this further and create classes to represent pages, but this might give you an idea of where to start. Using this approach allows you to keep all the data handling in the same PHP script, and makes the data available to other functions in the same script.
You want to use a flow such as
if (isset $_POST){
//do the data processing and such
}
else {
/show entry form
}
That's the most straight forward way I know of to stay on the same page and accept for data.