Storing multiple inputs with the same name in a CodeIgniter session - php

I've posted this in the CodeIgniter forum and exhausted the forum search engine as well, so apologies if cross-posting is frowned upon.
Essentially, I've got a single input, set up as <input type="text" name="goal">. At a user's request, they may add another goal, which throws a duplicate to the DOM. What I need to do is grab these values in my CodeIgniter controller and store them in a session variable. My controller is currently constructed thusly:
function goalsAdd(){
$meeting_title = $this->input->post('topic');
$meeting_hours = $this->input->post('hours');
$meeting_minutes = $this->input->post('minutes');
$meeting_goals = $this->input->post('goal');
$meeting_time = $meeting_hours . ":" . $meeting_minutes;
$sessionData = array(
'totaltime' => $meeting_time,
'title' => $meeting_title,
'goals' => $meeting_goals
);
$this->session->set_userdata($sessionData);
$this->load->view('test', $sessionData);
}
Currently, obviously, my controller gets the value of each input, writing over previous values in its wake, leaving only a string of the final value. I need to store these, however, so I can print them on a subsequent page.
What I imagine I'd love to do is extend the input class to be able to call $this->input->posts('goal'). Eventually I will need to store other arrays to session values. But I'm totally open to implementation suggestion.
Thanks so much for any help you can give.

You'd want to use this in your form:
<input type="text" name="goal[]">
You can then get the values in the Controller via:
$goal = $this->input->post('goal');
And then set the variable in the session via:
$this->session->set_userdata('goal', $goal);
If you want to retrieve it again. do this via:
$goal = $this->session->userdata('goal');
You'll have something like this:
$goal[0] = 'first goal';
$goal[1] = 'second goal';
Please try it first :)

Related

Trying to print values in multidimensional array to form as presets values

I'm currently working on a project where my current goal is to print information about the specific user on the final checkout form inputs.
First off I gather the information of the specific user through a public function:
public function getUserAddress($dbh)
{
$sql = "SELECT street, zip, city FROM address WHERE user_id=:user";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':user', $this->uid);
$stmt->execute();
$userAddress = $stmt->fetchAll(PDO::FETCH_ASSOC);
$this->userAddress = $userAddress;
return $this->userAddress;
}
Then I store the information in a variable I call $userAddress
$userAddress = $user->getUserAddress($dbh);
Since the user has two addresses, both with a "Street", "City" & "Zip" I'm storing both arrays in $templateData. This way I can specify what index should be printed out in which input tag instead of having to create a new function for each slot.
$templateData['user']['address'] = $userAdress['street']." ".$userAddress['city']." ".$userAddress['zip'];
However, printing these out seems near impossible. When I var_dump
$templateData['user']['address']
I only seem to be getting 2 empty strings and nothing else.
This is just code from my Checkout.controller but somehow the information doesn't seem to be found in my template page. All routes and includes are correct so dw about that.
I'm quite new to all this so I'd appreciate any help I can get!
Image of how the information should be presented https://gyazo.com/40fa06832207bd785ee038af4962bb1e
So in this case: "Postort" = "City" & "Gatuadress" = "Street"
PDO::fetchAll(PDO::FETCH_ASSOC) will return an array of associative arrays; so to access the individual elements you need something like:
$userAdress[0]['street']." ".$userAddress[0]['city']." ".$userAddress[0]['zip']
I could alaways define every single one of them specifically although it seems far fetched. Something like this:
$templateData['user']['address'][0]['street'] = $userAddress[0]['street'];
$templateData['user']['address'][0]['city'] = $userAddress[0]['city'];
$templateData['user']['address'][0]['zip'] = $userAddress[0]['zip'];
$templateData['user']['address'][1]['street'] = $userAddress[1]['street'];
$templateData['user']['address'][1]['city'] = $userAddress[1]['city'];
$templateData['user']['address'][1]['zip'] = $userAddress[1]['zip'];
I'm basically looking for another solution which doesn't require so much repetition.

Grab random value the remove from array

I am wanting to use a form confirmation to display a single use code and then discard the code so it wont be used again. So far this is what I have:
$codes = array(
'810',
'0190',
'1924',
'481',
'2941',
'8777',
'092',
'432',
'984',
'172',
'8483'
);
$rand_code = array_rand($codes);
$code_gen = $codes[$rand_code];
return $confirmation = 'Here is your code:' . $code_gen;
This shows me a random code each time I submit the form so it works perfect. I need to actually store that code and not use it again. What would be my best solution? Any help would be greatly appreciated.
Shuffle to get a random one, then pop it out, bam.
shuffle($codes);
while($code_gen = array_pop($codes)){
return $confirmation = 'Here is your code:' . $code_gen;
}
If you prepend the datetime to the ticketnumber then you are guaranteed that your number is not used again without needing to store it. (unless we have time travellers).
e.g. 110912032634 = ticket 1 and 110912032785 = ticket 2
If you mean by "later on" in the session, use sessions, etc...
If you mean by "later on" : after a month to collect data, then store it in a database

Preserving $_POST variables when paginating

I have a simple list of orders which a user can filter by status (open,dispatched,closed). The filter dropdown triggers a post to the server and sends the filter value through. Orders are listed out 10 to a page with pagination links for any results greater than 10. Problem is when I click the pagination links to view the next page of results the filter value in the post is lost.
public function filter_orders() {
$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
$filter = $this->input->post('order_status_filter');
$config = array();
$config["base_url"] = base_url() . "control/orders/filter_orders";
$config["per_page"] = 10;
$config['next_link'] = 'Next';
$config["uri_segment"] = 4;
$config['total_rows'] = $this->model_order->get_all_orders_count($this->input->post('order_status_filter'));
}
How can I make the pagination and filter work together. I've thought about injecting a query string in to the pagination links but it doesn't seem like a great solution.
The answer is very simple, use $_GET. You can also use URI segments.
i.e, index.php/cars/list/5/name-asc/price-desc'
The main reason you'll want to use $_GET is so you can link other users so they see the same result set you see. I'm sure users of your web app will want this functionality if you can imagine them linking stuff to each other.
That said, it would be ok to ALSO store the filters in the session so that if the user navigates away from the result set and then goes back, everything isn't reset.
Your best bet is to start a session and store the POST data in the session. In places in your code where you check to see if the user has sent POST data, you can check for session data (if POST is empty).
In other words, check for POST data (as you already do). If you got POST data, store it in the session. If a page has no POST data, check to see if you have session data. If you do, proceed as if it was POSTed. If you have both, overwrite the session with POST. You'll want to use new data your user sent you to overwrite older data they previously sent.
You either put everything in $_GET or if the data is sensible, put it in $_SESSION. Then it travels between pages.
In your case there seem to be no reason to put your filter data anywhere else than in $_GET.
A query string does seem the best solution. You could store it in the session or in cookies as well, but it makes sense to also store it in the query string.
Store it in cookies or the session if you want to remember the user's choice. Which seems like a friendly solution. It allows the user to keep their settings for a next visit, or for another page.
Store it in the query string, because going to 'page 2' doesn't tell you anything if you don't know about filters, page size or sorting. So if a user wants to bookmark page 2 or send it by e-mail, let them be able to send a complete link that contains this meta information.
Long story short: Store it in both.
maybe its not a right answer but, give it a try
<?php
// example url
$url = "index.php?page=6&filter1=value1&filter2=value2";
// to get the current url
//$url = "http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
// change the page to 3 without changing any other values
echo url_change_index( $url, "page", 3 );
// will output "index.php?page=3&filter1=value1&filter2=value2"
// remove page index from url
echo url_change_index( $url, "page" );
// will output "index.php?filter1=value1&filter2=value2"
// the function
function url_change_index( $url, $name = null, $value = null ) {
$query = parse_url( $url, PHP_URL_QUERY );
$filter = str_replace( $query, "", $url );
parse_str( $query, $parsed );
$parsed = ( !isset( $parsed ) || !is_array( $parsed ) ) ? array() : $parsed;
if ( empty( $value ) ) {
unset( $parsed[$name] );
}
else {
$parsed[$name] = $value;
}
return $filter.http_build_query( $parsed );
}
?>

MongoDB Login system & sessions in PHP

I am using MongoDB on my PHP website to keep hold of my registered users, and their login. So far, so good.
When I log in, I am using the following (simplified):
$login = $collection->findOne(array("mail" => $mailIn, "pass" => $passIn));
if($login) {
$_SESSION["gatekeeper"] = $login['_id'];
}
and when I register, the following:
$collection->insert($obj);
mkdir("$appDirectory/users/" . $obj["_id"]);
$_SESSION["gatekeeper"] = $obj["_id"];
The whole system is working good, but there is something that is bugging me: take a look at the JSON derived from this in the session manager:
"{\"gatekeeper\":{\"$id\":\"505f1cd25c73959504000000\"}}" (redis)
array(1) { ["$id"]=> string(24) "505f1cd25c73959504000000" } (php var dump - gatekeeper)
as you can see, it's storing it as an associative array $id->id.
of course it would be much better to have simply gatekeepeer->id.
How can I change this easily? I honestly find it confusing because of this "$id" that makes my PHP confused a bit, and confuses me as well.
Basically the annoyance is when I have to retrieve the gatekeeper:
$gatekeeper = $_SESSION["gatekeeper"];
$userID = $gatekeeper['$id']; //WILL work
$userID = $gatekeeper; //WON'T WORK
it would be much simpler (and better) to just have:
$userID = $_SESSION["gateID"];
$userName = $_SESSION["gateName"];
....
instead of:
$gatekeeper = $_SESSION["gatekeeper"];
$userID = $gatekeeper['$id'];
$userName = $gatekeeper['name'];
since the $_SESSION always refer to the same session there is no need to have an array inside the array.
Thanks in advance.
_id contains MongoId instance
so you need to convert it into string before assign into session variable
As below
$_SESSION["gatekeeper"] = (string) $obj["_id"]

OOP related question

I'm trying to improve my understanding on OOP^^
If I call this file...
set_organization.php file:
$organization = new Organization( );
$organization->name = 'Name here';
$organization->founder = 'Founder here';
then I access it again, are the name, and founder already set? Or should I put unset to ensure it's empty, like fresh start again? I'm kind of confused whether I need to unset it something like this:
$organization = new Organization( );
$organization->name = 'Name here';
$organization->founder = 'Founder here';
unset($organization);
to avoid query related bugs...please help.
Thanks!
Each time you call new Organization( ); a new instance is created that has nohing to do with any previous ones (except static class members).
If this is done in sepereate requests even more so, but this is because each request runs it's own script.

Categories