Working with session in PHP - php

I have a form from which i take some datas and using session i want to keep that datas as a history on my page, and also when i click on one line from my history i want my datas to be autocomplete in my form. I saw an example on one page and i tried doing it to apply to what i want but it's not quite functional.
This is my code for the form:
<form method="get">
Create:<br><br>
Name:<br> <input type="text" id="name" value="" /><br>
surname:<br> <input type="text" id="surname" value="" /><br>
Sex:<br> <div class="select-wrapper">
<select name="sex" id="sex">
<option value="">- Sex -</option>
<option value="woman">Woman</option>
<option value="male">Male</option>
</select>
</div>
Role: <div class="select-wrapper">
<select name="rol" id="rol">
<option value="">- Role -</option>
<option value="visitor">Visitor</option>
<option value="Professor">Professor</option>
<option value="Student">Student</option>
</select>
</div>
Text color: <div class="select-wrapper">
<select name="cul" id="cul">
<option value="">- Text color -</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
</select>
</div>
Font text: <div class="select-wrapper">
<select name="font" id="font">
<option value="">- Font text -</option>
<option value="15px Arial">Arial</option>
<option value="15px Times New Roman">Times New Roman</option>
<option value="15px Georgia">Georgia</option>
<option value="15px Comic Sans MS">Comic Sans MS</option>
<option value="15px Lucida Sans Unicode">Lucida Sans Unicode</option>
<option value="15px Courier New">Courier New</option>
</select>
</div>
Format : <div class="select-wrapper">
<select name="format" id="format">
<option value="">- Format -</option>
<option value="portrait">Portrait</option>
<option value="landscape">Landscape</option>
</select>
</div>
Style text: <div class="select-wrapper">
<select name="stil" id="stil">
<option value="">- Style text -</option>
<option value="stil1">Stil1</option>
<option value="stil2">Stil2</option>
<option value="stil3">Stil3</option>
<option value="stil4">Stil4</option>
<option value="stil5">Stil5</option>
<option value="stil6">Stil6</option>
</select>
</div>
</form>
And this is where i tried to use session:
<?php
session_start();
$createpas = parseRequest();
storecreatepas($createpas);
include "form.php";
$createpases = $_SESSION['createpases'];
include "history.php";
function storecreatepas($createpas) {
if (!isset($_SESSION['createpases'])) {
$_SESSION['createpases'] = [];
}
if (!$createpas->isEmpty()) {
$_SESSION['createpases'][] = $createpas;
}
}
function parseRequest() {
$createpas = new createpasRequest;
$createpas->cul = !empty($_GET['cul']) ? $_GET['cul'] : "";
$createpas->font = !empty($_GET['font']) ? $_GET['font'] : "";
$createpas->format = !empty($_GET['format']) ? $_GET['format'] : "";
$createpas->stil = !empty($_GET['stil']) ? $_GET['stil'] : "";
return $createpas;
}
/**
* createpas request
*/
class createpasRequest
{
public $cul = "";
public $font = "";
public $format = "";
public $stil = "";
function toQueryString() {
$params = [
'cul' => $this->cul,
'font' => $this->font,
'format' => $this->format,
'stil' => $this->stil
];
return http_build_query($params);
}
function isEmpty() {
return !$this->cul || !$this->font || !$this->format || !$this->stil;
}
function culAsObject() {
return new DateTime($this->cul);
}
function fontAsObject() {
return new DateTime($this->font);
}
function formatAsObject() {
return new DateTime($this->format);
}
function stilAsObject() {
return new DateTime($this->stil);
}
}
And the display code:
<ul>
<?php
foreach ($createpases as $s) {
?>
<li><a href="search.php?<?php echo $s->toQueryString() ?>">
<?php echo $s->cul?> - <?php echo $s->font?> - <?php echo $s->format?> - <?php echo $s->stil?>
</a></li>
<?php
}
?>
</ul>
It works just fine until some point. It gets my datas from my form posts them on the page but when i click on them they don't autocomplete in in my form. And also if i want the options to be unique in the list how can i do that? Right now if i complete the same datas 2 or 3 times they appear multiple times in my list.
Thank you for your help!

You need to start the session in the Form page and then check if the SESSION array contains the values to be echoed.
So your code will become:
<?php session_start();
if(!isset($_SESSION['name']){$_SESSION['name']=''}
if(!isset($_SESSION['sex']){$_SESSION['sex']=''}
if(!isset($_SESSION['rol']){$_SESSION['rol']=''}
?>
//this way you will not have issues on page first load before the user fills in the form
<form method="get">
Create:<br><br>
Name:<br> <input type="text" id="name" value="<?php echo $_SESSION['name']; ?>" /><br>
surname:<br> <input type="text" id="surname" value="" /><br>
Sex:<br> <div class="select-wrapper">
<select name="sex" id="sex">
<option value="" <?php if($_SESSION['rol']==''){echo 'selected'} ?>>- Sex -</option>
<option value="woman" <?php if($_SESSION['rol']=='woman'){echo 'selected'} ?>>Woman</option>
<option value="male" <?php if($_SESSION['rol']=='visitor'){echo 'selected'} ?>>Male</option>
</select>
</div>
Role: <div class="select-wrapper">
<select name="rol" id="rol">
<option value="" <?php if($_SESSION['rol']==''){echo 'selected'} ?>>- Role -</option>
<option value="visitor" <?php if($_SESSION['rol']=='visitor'){echo 'selected'} ?>>Visitor</option>
<option value="Professor"<?php if($_SESSION['rol']=='Professor'){echo 'selected'} ?>>Professor</option>
<option value="Student"<?php if($_SESSION['rol']=='student'){echo 'selected'} ?>>Student</option>
</select>
</div>
and so on.

It appears that your form does not auto-fill with the data because you do not have such a functionality implemented. This auto-complete functionality is not automatic, as in, the server does not do it for you.
Here is an example of what you need to do in order to get the autocomplete to work:
Name:<br> <input type="text" id="name" value="<?= $_SESSION['name'] ?>" /><br>
For the select to auto-complete, you'll need to do something like this:
<select name="cul" id="cul">
<option value="">- Text color -</option>
<option value="red" <? echo ($_SESSION['cul']==="red")?"selected='selected'":""; ?>>Red</option>
<option value="blue" <? echo ($_SESSION['cul']==="blue")?"selected='selected'":""; ?>>Blue</option>
<option value="black" <? echo ($_SESSION['cul']==="black")?"selected='selected'":""; ?>>Black</option>
</select>
This sets the value for each form element by directly setting the value / selected item using the $_GET data from a previous submission, or if there is no data, everything will be empty / default values.
Per a suggestion from one of the comments to this answer, I would like to point out that you must include "session_start()" to the top of the document if you wish to use the session variables on the document (if you have not done so already).
One question about the original question: is that first code block procedurally generated, or hand-typed?

Related

Keep values in <select> for loop after submit

I am trying to retain the values in my select with a for loop option if form is submitted incomplete. It inserts the values into database and functions perfectly fine but I don't want people to have to fill out all the for loop selects again if they submit the form incomplete.
if(!empty($_POST['height'])){
$height = $_POST['height'];
}
<select class="form-control selectpicker" name="height">
<option value="" disabled selected>Select Your Height</option>
<?php
for ($i=1; $i<=250; $i++)
{?>
<option value="<?php echo $i;?>"><?php echo $i;?>cm</option>
<?php
}
?>
</select>
I have my other select functioning perfectly:
<?php
if(isset($_POST['city'])){
$city = $_POST['city'];}?>
<select class=" form-control selectpicker" name="city" value="">
<optgroup label="Thailand">
<option disabled selected>Select A City</option>
<option
<?php
if (isset($city) && $city=="Bangkok") echo "selected";?>
>Bangkok</option>
<option <?php
if (isset($city) && $city=="Phuket") echo "selected";?>
>Phuket</option>
<option <?php
if (isset($city) && $city=="Pattaya") echo "selected";?>
>Pattaya</option>
</optgroup>
</select>
Essentially I want to achieve the same result as the City select but with the for loop in the Height select.
I have spent the last couple of days researching and trying to implement different codes and strategies to make it work but I still can't get it to function. Any help is greatly appreciated and if there is anymore code or explanation required I will be happy to provide it.
You have added value in $height. But in select, you haven't use it to retain selected value. change your drop-down for height as below-
if(!empty($_POST['height'])){
$height = $_POST['height'];
}
<select class="form-control selectpicker" name="height">
<option value="" disabled selected>Select Your Height</option>
<?php
for ($i=1; $i<=250; $i++)
{?>
<option value="<?php echo $i;?>" <?php if (isset($height) && $height==$i) echo "selected";?>><?php echo $i;?>cm</option>
<?php
}
?>
</select>

Get value of drop down menu and save as variable in PHP

I want to get the selected value of a drop down menu and save it as a variable. I tried the following as documented in another post, but it seems not working: echo $selected = $_POST['<?php $as->my_name(); ?>'];
Drop down:
<select name="<?php $as->my_name(); ?>">
<option value="">Select this</option>
<option value="91"<?php $mb->state('91'); ?>>91</option>
<option value="90"<?php $mb->state('90'); ?>>90</option>
<option value="89"<?php $mb->state('89'); ?>>89</option>
<option value="88"<?php $mb->state('88'); ?>>88</option>
<option value="87"<?php $mb->state('87'); ?>>87</option>
<option value="86"<?php $mb->state('86'); ?>>86</option>
<option value="85"<?php $mb->state('85'); ?>>85</option>
<option value="84"<?php $mb->state('84'); ?>>84</option>
<option value="83"<?php $mb->state('83'); ?>>83</option>
<option value="82"<?php $mb->state('82'); ?>>82</option>
</select>
Post the form:
You have to put the select option within form tags
<form method="post">
<select name="example">
<option></option>
</select>
<input type="submit" />
</form>
Get the posted value:
To get the value of this example you can use:
<?php
$selected = $_POST['example'];
echo $selected;
?>
To get the value in your case:
<select name="<?php echo $as->my_name(); ?>">
<option value="test">test</option>
</select>
<?php
$selected = $_POST[$as->my_name()];
echo $selected;
?>

array in php function undefined

For training purposes i need to make a function which tells me the 'travel cost' between 2 cities. The book tells me to type this function:
<?php
function travelcost($start, $destination)
{
$travelcost = array();
$travelcost[1] = array();
$travelcost[2] = array();
$travelcost[3] = array();
$travelcost[4] = array();
$travelcost[1][1] = 0;
$travelcost[1][2] = 30;
$travelcost[1][3] = 60;
$travelcost[1][4] = 90;
echo($travelcost[$start][$destination] . " Euro's");
}
?>
In addition i've created this form to ask for a start and a destination:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Start: <select name="start" value="true">
<option value="start[]">Amsterdam</option>
<option value="start[]">Utrecht</option>
<option value="start[]">Den Haag</option>
<option value="start[]">Rotterdam</option>
</select>
Destination: <select name="destination" value="true">
<option value="destination[]">Amsterdam</option>
<option value="destination[]">Utrecht</option>
<option value="destination[]">Den Haag</option>
<option value="destination[]">Rotterdam</option>
</select>
<p><input type="submit" name="calculate" value="Calculate"</p>
</form>
Followed by:
<?php
if(isset($_POST["start"])&& isset($_POST["destination"]))
{
travelcost($_POST['start'], $_POST['destination']);
}
?>
This gives me Undefined index: start[]
I know im doing it wrong, but i just can't see the logic in the function and the array. I assume the function is correct because it's right out of the book but i'm also not sure about that.
Can someone help me out?
This is wrong,
<option value="start[]">Amsterdam</option>
^ ^
It should be
<option value="start">Amsterdam</option>
or
<option value="Amsterdam">Amsterdam</option>
Same for all options in start and destination.
According to your function `travelcost(), your select should be
Start: <select name="start" value="true">
<option value="1">Amsterdam</option>
<option value="1">Utrecht</option>
<option value="1">Den Haag</option>
<option value="1">Rotterdam</option>
</select>
Destination: <select name="destination" value="true">
<option value="1">Amsterdam</option>
<option value="2">Utrecht</option>
<option value="3">Den Haag</option>
<option value="4">Rotterdam</option>
</select>

PHP: redirect to blog pages by selectbox on HTML form

I'm a newbie on PHP programming but I have to use it for a page in my blog that permit the users to search inside the blog using a radiobox and a selectbox. I've read some discussion about it but I can't find the error in my code.
This is my situation: I would permit a searching by brand or by model or by cc in my blog that talks about motorcycles, so I have a form with three radiobox that enables/disables the three selectboxes below. One for each category above-named. Clicking a button, the user will be redirected to the respective link /brand/ or /model/ or /cc/.
This is my HTML form:
<form name="admin" method="post" action="/search.php">
<input type="radio" name="rdo_brand" value="brand" id="r_brand" onclick="document.getElementById('r_model').checked=false;document.getElementById('r_cc').checked=false;document.getElementById('box_brand').disabled=false;document.getElementById('box_model').disabled=true;document.getElementById('box_cc').disabled=true;"> Search by brand
<input type="radio" name="rdo_model" value="model" id="r_model" onclick="document.getElementById('r_brand').checked=false;document.getElementById('r_cc').checked=false;document.getElementById('box_brand').disabled=true;document.getElementById('box_model').disabled=false;document.getElementById('box_cc').disabled=true;"> Search by model
<input type="radio" name="rdo_cc" value="cc" id="r_cc" onclick="document.getElementById('r_brand').checked=false;document.getElementById('r_model').checked=false;document.getElementById('box_brand').disabled=true;document.getElementById('box_model').disabled=true;document.getElementById('box_cc').disabled=false;"> Search by cc
Brand
<select name="brand" id="box_brand" />
<option value="-">-</option>
<option value="bmw">Bmw</option>
<option value="ducati">Ducati</option>
<option value="honda">Honda</option>
</select>
Model
<select name="model" id="box_model" />
<option value="-">-</option>
<option value="k1200gt">K1200GT</option>
<option value="monster">Monster</option>
<option value="silverwing>Silver Wing</option>
</select>
CC
<select name="cc" id="box_cc" />
<option value="-">-</option>
<option value="600">600</option>
<option value="900">900</option>
<option value="1200">1200</option>
</select>
<input type="submit" value="Search" id="btn_search" />
>/form>
And this is my search.php:
// Data recovery process
// I know it's not the better way but is the most simply for a newbie like me!
if (empty($_POST['brand']))
{
$brand = 'nothing';
}
else
{
$brand = $_POST['brand'];
}
if (empty($_POST['model']))
{
$model = 'nothing';
}
else
{
$model = $_POST['model'];
}
if (empty($_POST['cc']))
{
$cc = 'nothing';
}
else
{
$cc = $_POST['cc'];
}
// Replacing spaces in acquired variables
$brand = str_replace(" ", "-", $brand);
$model = str_replace(" ", "-", $model);
$cc = str_replace(" ", "-", $cc);
// Control process
if ($brand <> 'nothing')
{
header("location: mysite.com/categories/brands/$brand/");
exit;
}
else
{
if ($model <> 'nothing')
{
header("location: mysite.com/categories/models/$model/");
exit;
}
else
{
header("location: mysite.com/categories/cc/$cc/");
exit;
}
}
I think the code is correct but, obviously, it's not, because doesn't work completely. If I check the rdo_brand and I select one of the option inside the brand (bmw for example), the redirect works fine to mysite.com/categories/brands/bmw/... but if I check the rdo_model and I select one of the option inside the model, the redirect wrongly take me to mysite.com/categories/cc/nothing/
I can't understand! Why is this happening?
Try fixing the typos in the html code (see bellow)
<form name="admin" method="post" action="/search.php">
<input type="radio" name="rdo_brand" value="brand" id="r_brand" onclick="document.getElementById('r_model').checked=false;document.getElementById('r_cc').checked=false;document.getElementById('box_brand').disabled=false;document.getElementById('box_model').disabled=true;document.getElementById('box_cc').disabled=true;"> Search by brand
<input type="radio" name="rdo_model" value="model" id="r_model" onclick="document.getElementById('r_brand').checked=false;document.getElementById('r_cc').checked=false;document.getElementById('box_brand').disabled=true;document.getElementById('box_model').disabled=false;document.getElementById('box_cc').disabled=true;"> Search by model
<input type="radio" name="rdo_cc" value="cc" id="r_cc" onclick="document.getElementById('r_brand').checked=false;document.getElementById('r_model').checked=false;document.getElementById('box_brand').disabled=true;document.getElementById('box_model').disabled=true;document.getElementById('box_cc').disabled=false;"> Search by cc
Brand
<select name="brand" id="box_brand" />
<option value="-">-</option>
<option value="bmw">Bmw</option>
<option value="ducati">Ducati</option>
<option value="honda">Honda</option>
</select>
Model
<select name="model" id="box_model" />
<option value="-">-</option>
<option value="k1200gt">K1200GT</option>
<option value="monster">Monster</option>
<option value="silverwing">Silver Wing</option>
</select>
CC
<select name="cc" id="box_cc" />
<option value="-">-</option>
<option value="600">600</option>
<option value="900">900</option>
<option value="1200">1200</option>
</select>
<input type="submit" value="Search" id="btn_search" />
</form>

Retrieve stored radio button value from database

I have drop down list in my EditDevice view file which I have loaded values from the database.
<select name="TrackerType" name="Type" id="Type" style="width:68% !important;">
<option <?php echo ($devicearray['type']=='mobile'?'selected="selected"':''); ?>>mobile</option>
<option <?php echo ($devicearray['type']=='third party'?'selected="selected"':''); ?>>third party</option>
<option <?php echo ($devicearray['type']=='other'?'selected="selected"':''); ?>>other</option>
Now I want to retrieve the selected value in my controller file.
$NewDeviceArray["Type"] = $this->input->post("Type");
But I don't get the selected value when I print the Type.
var_dump($NewDeviceArray["Type"]);
So, my question is how to get the selected value from drop down to a variable in controller.
try this
<select name="Type" id="Type" style="width:68% !important;">
<option value="mobile" <?php echo ($devicearray['type']=='mobile'?'selected="selected"':''); ?>>mobile</option>
<option value="third party" <?php echo ($devicearray['type']=='third party'?'selected="selected"':''); ?>>third party</option>
<option value="other" <?php echo ($devicearray['type']=='other'?'selected="selected"':''); ?>">other</option>
</select>

Categories