How to save data to session - php

When the user clicks the "Select" link, I would like whatever is selected to be saved to the session. Then another view will display all of the items stored in the session.
How can I do this? Or is there better solution or approach to use with this application?
Here is my current code:
<?php
foreach($query as $row){
echo $row ->firstname;
echo $row ->lastname;
echo "<a href=".base_url()."index.php/controller/function/$row->username /> Select </a>"
}
?>

This should be in your controller:
function my_function($username) {
$users = json_decode($this->session->userdata('users'), true);
$users[] = $username;
$this->session->set_userdata('users', json_encode($users));
print_r($this->session->userdata('users'));
}
Make sure the session library is loaded. Autoload suggested.

For example, on the top of your page:
<?PHP
session_start();
if (isset($_SESSION['yourvar']))
echo $_SESSION['yourvar'];
else
$_SESSION['yourvar'] = 10;
?>

Related

How to add GET and remove

I have more GET variables. I want the variables to be added after clicking. And after clicking again I want them to be removed from GET. I am a beginner and I don't know how to do it.
<?php
$tab_array['name1']=1;
$tab_array['name2']=2;
$tab_array['name3']=3;
$tab_array['name4']=4;
$url=$_SERVER[QUERY_STRING];
if(!empty($url)){
$url="&".$url;
}
?>
<form action="" method="GET">
<?php
foreach($tab_array as $key => $val){
?>
<?php echo $key;?>
<?php
}
?>
</form>
Someone will help?
Sorry for my bad English...
Code
<?php
$tab_array['name1']=1;
$tab_array['name2']=2;
$tab_array['name3']=3;
$tab_array['name4']=4;
$url='?'; // this will call the current url
// $_GET is the array your submitted data will be strored in - initially empty []
?>
<form method='GET'><!-- you actually don't need a form, since only input, textarea, etc get submitted -->
<?php
// save current state, so you can modify it for every possible click
$current_get = $_GET;
foreach($tab_array as $key => $value) {
$new_get = $current_get;
// check if the current key is already in your set ($new_get)
if (array_key_exists($key, $new_get)) { // it is, so remove
unset($new_get[$key]);
} else { // it is not, so add
$new_get[$key] = $value;
}
// build your query_string (from $new_get array)
$query_string = http_build_query($new_get);
// you can use variables in string when its encapsulated in double quotes: "text $var"
echo "<a href='$url$query_string'>$key</a>";
// more readable:
// echo "<a href='{$url}{$query_string}'>{$key}</a>";
// not need but looks better :P
echo '<br />' . PHP_EOL;
}
?>
</form>
A little more
there is a shortcut for <php echo $var ?> which is just <?= $var ?>
Links
array_key_exists
unset
http_build_query

POST array data in php

I'm trying to post array data to another php, but it doesn't work..
here is my code below.
in func.php
function search($x, $y)
{
...
$martx = array();
$marty = array();
foreach($load_string->channel as $channel) {
foreach($channel->item as $item) {
array_push($martx, $item->mapx);
array_push($marty, $item->mapy);
}
}
echo"<form method=post action='map.php'>";
for($i = 0; $i < 8; $i++)
{
//echo $martx[$i]."<br/>";
//echo $marty[$i]."<br/>";
echo "<input type='hidden' name='martx[]' value='".$martx[$i]."'>";
echo "<input type='hidden' name='marty[]' value='".$marty[$i]."'>";
}
echo "</form>";
header("location: map.php?x=$x&y=$y");
}
martx and marty have data from parsed xml $load_string
And I want to post these data to map.php by form with POST. So, I expect that I can use two arrays martx and marty in map.php like $_POST[martx][0]..
But when I run this code, page remains in func.php, instead of redirecting to map.php
Am I make some mistake?
Thanks in advance.
========================================================================
Thank you all for your kind concern and helpful advice!
I edit my code with your advice,
I delete all echo with using javascript
And I add submit code
here is my code below
....
$martx = array();
$marty = array();
foreach($load_string->channel as $channel) {
foreach($channel->item as $item) {
array_push($martx, $item->mapx);
array_push($marty, $item->mapy);
}
}
?>
<form method='post' action='map.php?x=<?=$x?>&y=<?=$y?>' id='market'>
<script language="javascript">
for(i = 0; i < 8; i++)
{
document.write('<input type="hidden" name="martx[]" value="<?=$martx[i]?>">');
document.write('<input type="hidden" name="marty[]" value="<?=$marty[i]?>">');
}
document.getElementById('market').submit();
</script>
</form>
<?php
//header("location: map.php?x=$x&y=$y");
}
With this code, page redirect to map.php successfully.
But I can't get data like $_POST['martx'][i] in map.php
I think document.write line cause problem
when I write code like
document.write('<input type="hidden" name="martx[]" value="$martx[i]">');
result of $_POST['martx'][i] is "$martx[i]"
Is any error in this code?
I want to use POST method but if I can't post data with POST,
then I'll use session-method as #Amit Ray and #weigreen suggested.
thanks again for your concern.
First, You try to use header('location: xxx') to redirect user to another page.
As the result, you are not submitting the form, so you won't get data like $_POST[martx][0] as you expect.
Maybe you should try using session.
I can see some errors that you are making when you are doing header redirect. There should be no output before you call header redirect but you are doing echo before redirect.
use session to tackle this issue
function search($x, $y)
{
...
$martx = array();
$marty = array();
foreach($load_string->channel as $channel) {
foreach($channel->item as $item) {
array_push($martx, $item->mapx);
array_push($marty, $item->mapy);
}
}
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$_SESSION["martx"] = $martx;
$_SESSION["marty"] = $marty;
header("location: map.php"); exit;
then in map.php you can retrieve the session variables
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$martx = $_SESSION["martx"];
$marty = $_SESSION["marty"];
Then you can use a for loop or foreach loop to iterate through the values

How to use php fetched data into html using jquery post

Hi i have a function in jquery and using $.Post to send data on a php file where my query is working fine and sending data back
js
function send_agenda_data(cidade_data){
var data = {'cidade_data':cidade_data};
$.post('includes/agenda_data.php',data,function(info){
});
}
This function works fine and when i alert the data coming back that also works fine
here is php
<?php
include_once("connection.php");
$cidade_data = $_POST['cidade_data'];
if (isset($cidade_data)) {
$sql = mysql_query("select * from agenda where cidade = '$cidade_data'", $con) or die(mysql_error());
if (mysql_num_rows($sql) > 0) {
while ($data = mysql_fetch_object($sql))
{
$date = $data->data;
$cidade = htmlentities($data->cidade);
$estado = htmlentities($data->estado);
$local = htmlentities($data->local);
$endereco = htmlentities($data->endereco);
$site_local = htmlentities($data->site_local);
$site_ingresso = htmlentities($data->site_ingresso);
$endereco = htmlentities($data->endereco);
}
}
else{
echo "No Data";
}
}
?>
this works fine if i use directly using php and echo the variables in tags now
$.post('includes/agenda_data.php',data,function(info){
//need data here
});
i want to know how i can get the php returned data in js here and how i assign that data into tags. also want to know there is while loop in php is here will be also loop to populate all rows ?
if i use direct php in my webpage then i can use like this in while loop
<div><?php echo $date; ?></div>
<div><?php echo $cidade; ?></div>
<div><?php echo $estado; ?></div>
<div><?php echo $local; ?></div>
.
.
.
how can i get in $.Post case
Your loop is somewhat incorrect. You're simply fetching each row's data, and then overwriting the previous row's data in all those variables. You should be building an array of results, which you can then send over to the client-side JS code. e.g. something like
$data
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode($data);
On the client side, you'll receive an array of objects you can iterate over:
$.post('includes/agenda_data.php',data,function(data){
$.each(data, function(idx, row) {
$('#date').innerHTML = row['date'];
...
});
});
exactly what you do in that JS loop is up to you.
As well, note that your PHP code is vulnerable to SQL injection attacks.
$.post is an AJAX call, thus you need to echo the result in PHP, to make sure you can use the results.
Try using
echo json_encode($your_data)
And to use the data in client side (browser), you can use
http://api.jquery.com/jQuery.parseJSON/
That parseJSON is used so you can use the data easier.
Why not use jQuery to fill the contents of the div by assigning a class as in this example:
<div class="date"><?php echo $date; ?></ div>
<div class="cidade"><?php echo $cidade; ?></ div>
<div class="estado"><?php echo $estado; ?></ div>
<div class="local"><?php echo $local; ?></ div>
and with jQuery, the success of $.post retrieve the information returned and integrate like this.
$('.date').html(info[0]['date']);

Sharing a session variable between multiple php scripts

My question is that when I copy my array elements between different PHP scripts using session variables, nothing gets printed out. The following are my two PHP files.
file1.php
<?PHP
session_start();
$SQL = "SELECT * FROM tblquestions";
if ($db_found) {
$result = mysql_query($SQL);
$numRows = mysql_num_rows($result); //return number of rows in the table
echo '<FORM NAME ="form1" METHOD ="POST" ACTION ="file2.php">';
for ($i = 1; $i <= 2; $i++)
{
$db_field = mysql_fetch_assoc($result);
$qID[$i] = $db_field['QID'];
$question[$i] = $db_field['Question'];
$A[$i] = $db_field['qA'];
$B[$i] = $db_field['qB'];
$C[$i] = $db_field['qC'];
echo '<P>';
print $question[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'A'>";
print $A[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'B'>";
print $B[$i];
echo '<P>';
echo "<INPUT TYPE = 'Radio' Name = '".$qNum."' value= 'C'>";
print $C[$i];
//if (isset($_POST[$name_Value]))
$survey_Answers[$i-1] = $_POST[$qNum];
print '</BR>'.$survey_Answers[$i-1]."</BR>";
$question_Number = ltrim($qNum,'q');
$question_Number++;
$qNum ='q'.$question_Number;
}
echo '<p>';
$_SESSION['answers'] = $survey_Answers;
echo '<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Click here to vote">';
echo '</form>';
?>
On my Second file (file2.php), I have the following:
<?PHP
session_start();
if (isset($_POST['Submit1'])) {
$results = $_SESSION['answers'];
print $results[0];
}
?>
However, on my file2.php I get the following error: Undefined offset: 0 and nothing gets printed out.
echo '<p>';
session_start();
that canĀ“t work, session_start has to be called before any output!
if you put session_start() at the beginning of your file, you should be all right.
To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
source: http://php.net/manual/en/function.session-start.php
You need to call session_start() before you output anything. It is a best practice to place it at the beginning of your script before you output anything.
Please Add the below code to every page you want to use the session data.Other wise it will return an error .
<?php
session_start();
?>
in file1.php session_start(); should be first line of the code same as in file2.php
There is a comment on the PHP manual page for session_start() which sounds very similar to your problem. http://php.net/manual/en/function.session-start.php#65944
It says that an array with integer keys assigned either as a straight array or using the integers will fail and the data will not pass to the next page.
Modify your code to use strings as keys.

Yii multi model with HAS_MANY Tabular form

I have been trying to find a solution to something that I believe is rather simple? What I would like to do is create a tabular form to collect some records for a survey.
Table: survey_record
id
meter_id
status_id
create_time
create_user
Table: survey_inspection
id
survey_record_id (FK)
bay_id
bay_usage_id
So table survey_inspection HAS_MANY inspections from survey_record.
Assuming an inspector is doing a survey for meter_id = 1001, the user identifies the status_id of the meter then, they have to fill in 4 inspection entries, as 1001 has 4 bays.
To generate the 4 bays I simply created a for loop. Which works fine.
View: _form.php
...
$meter=Meter::model()->findByPk($model->meter_id);
$bays = count($meter->bays); //retrieves the number of inspections required
<?php echo $form->dropDownListRow($model,'status_id',$model->getStatusId(),array('prompt'=>'Select Status ...')); ?>
...
<?php for ($i = 1; $i <= $bays; $i++): ?>
<?php echo $form->textFieldRow($inspection, "[$i]bay_id", array('readonly'=>true, 'value'=>"$i", 'class'=>'span1')); ?>
<?php echo $form->dropDownListRow($inspection, "[$i]bay_usage_id", $inspection->getUsageId(), array('prompt'=>'Bay Status ...') ); ?>
<?php endfor; ?>
...
However when I submit the form I am only receiving two (not four) results and I can't seem to display the validated fields correctly. So here's the famous controller file:SurveyRecordController.php
public function actionCreate($survey_id, $meter_id)
{
$model=new SurveyRecord;
$inspection = new SurveyInspection;
$model->survey_id = (int)$survey_id;
$model->meter_id = (int)$meter_id;
if(isset($_POST['SurveyRecord'], $_POST['SurveyInspection']))
{
$model->attributes=$_POST['SurveyRecord'];
$valid= $model->validate();
$i=1;
foreach($_POST['SurveyInspection'][$i] as $inspection)
{
$inspection = new SurveyInspection;
$inspection->bay_id =$_POST['SurveyInspection'][$i]['bay_id'];
$inspection->bay_usage_id =$_POST['SurveyInspection'][$i]['bay_usage_id'];
$valid= $inspection->validate() && $valid;
echo '<br/><br/><br/><pre>';
print_r($_POST['SurveyInspection'][$i]);
echo '</pre>';
if($valid)
{
if($model->save(false))
{
$inspection->survey_record_id = $model->id;
$inspection->save(false);
$this->redirect(array('/meter'));
}
}
$i++;
//$inspection->attributes=$_POST['SurveyInspection'][$i];
}
}
$this->render('create',array(
'model'=>$model,
'inspection'=>$inspection,
));
}
I have a funny feeling that I may not be doing the foreach loop correctly as when I view the array $_POST['SurveyInspection'][$i] I am only returned with two entries when there should be four.
Some information that may be helpful:
PHP version: 5.4.14
Yii version: 1.1.13
PostgreSQL version: 9.1.9
Thank you kindly :)
To my knowledge i think for the validation u have bypassed the default validation by passing
false to save method (ex : $model->save(false)) and u are also using yii's validate function . I think u try removing the false parameter and just use save() for the validation issue
The foreach loop is wrong. You can make it proper and a bit cleaner:
foreach($_POST['SurveyInspection'] as $i => $value)
{
$inspection = new SurveyInspection;
$inspection->bay_id = $value['bay_id'];
$inspection->bay_usage_id = $value['bay_usage_id'];
...
$i++ is not needed, as foreach will loop every element.
I've taken a completely different approach, valuable suggestions are always welcome :)
Hope this will be helpful for some of you.
Controller:
public function actionCreate($survey_id, $meter_id)
{
$bays = $this->getBayCount($meter_id);
for ($i=1;$i<=$bays;$i++)
{
$model=new SurveyRecord;
$model->survey_id = (int)$survey_id;
$model->meter_id = (int)$meter_id;
${'inspection_'.$i} = new SurveyInspection($i);
if(isset($_POST['SurveyRecord'], $_POST["SurveyInspection"][$i]))
{
$model->attributes = $_POST['SurveyRecord'];
${'inspection_'.$i}->attributes = $_POST["SurveyInspection"][$i];
echo '<br/><br/><br/><pre>';
print_r(${'inspection_'.$i}->attributes);
echo '</pre>';
}
}
for ($i=1;$i<=$bays;$i++)
{
${'inspection_'.$i} = new SurveyInspection($i);
$inspection['inspection_'.$i] = ${'inspection_'.$i};
}
$this->render('create',array(
'inspection'=>$inspection,
'model'=>$model
));
}
View:
...
<div class="control">
<?php echo $form->dropDownListRow($model,'status_id',$model->getStatusId(),array('prompt'=>'Select Status ...')); ?>
<?php
$meter=Meter::model()->findByPk($model->meter_id);
$bays = count($meter->bays);
?>
<?php for ($i=1; $i<=$bays; $i++): ?>
<table>
<tr>
<td><?php echo $form->textFieldRow($inspection["inspection_$i"], "[$i]bay_id",
array('readonly'=>true, 'value'=>"$i", 'class'=>'span1')); ?></td>
<td><?php echo $form->dropDownListRow($inspection["inspection_$i"], "[$i]bay_usage_id", $inspection["inspection_$i"]->getUsageId(),
array('prompt'=>'Bay Status ...') ); ?></td>
</tr>
</table>
<?php endfor; ?>
</div>
...
Credit: http://yiiblog.info/blog/index.php/post/108/Rename+ACtiveRecord+$_POST+array's+Name+to+update+multimodels
Note: There's still some work to be done on the view/controller (doesn't seem to be able to select on $_POST for my dropdowns on second model), will post once I have fixed it.
Thanks for your help #PeterM and #Ninad for your input.

Categories