I want each time a file is called, to make a new sub-array. So say if I have a URL like http://example.com?name=[INPUT] , every time it calls it will add a new element to the array. With $users being the main array. EA:
$users[0][name] = "John"
$users[1][name] = "Sally"
Each call to the input will create a new $users[INCRIMENTAL_KEY][name] value.
A simple solution would be
$user[]['name'] = $name;
Although if all you are storing is a single item it would be even simpler to do
$user[] = $name;
Although if you want to keep this information across page executions and not be effected by WHO is running the page, you are going to have to keep the information in a database and just add a new row to a table each time the script is run.
You need a persistent way to track the array's data, whether that be sessions, database or files (depends on how long you want persistence for and whether it should be public or per-user).
Session example:
session_start();
// Initialise an empty array
if (empty($_SESSION['users'])) {
$_SESSION['users'] = [];
}
// Add each name to the session array
if (isset($_GET['name'])) {
$_SESSION['users'][] = ['name' => $_GET['name']];
}
Session would of course be per-user and per-session. You could use cookies and/or sessions for a longer persistence per-user, or use flatfile/database storage for more control and non-ending persistence.
Related
Trying to get each $_GET from url string request in an array.
So if user A visits site with www.example.com?user="bob", pass to array 'users'.
Now alice visits with www.example.com?user=alice, pass to array 'users'.
I have tried this:
<html>
<body>
<?php>
$Users = array();
$Member = $_GET['name'];
$Users[] = $Member;
print_r($Users);
?>
</body>
</html>
But I still get only the last value, that is..Array( [0] => "Alice" )
Mmm, so do I need a function, to fill the array?
Thnx
try with SESSION ,
<?php
session_start();
$Users = array();
$Member = $_GET['name'];
$_SESSION['users'][] = $Member;
print_r($_SESSION['users']);
?>
For more informations, you can take a look at the Session Handling https://www.php.net/manual/en/book.session.php section of the manual, that gives some useful informations.
PHP creates new process for every web request. Subsequent requests share no memory or other resources. Each time PHP process is created, new memory pool is initialized for this process. So it is impossible to use memory as a storage for subsequent requests.
You need some kind of permanent storage like file on disk or a database. One process can write to this storage and the other one can read from it.
I want to add different stuffs to costumers cart but before adding the stuff transition in the database costumer must pay and then redirect to another page after Successful transition i need the chosen stuffs id's i tried using $_POST but the browser does not send the post value because of payment system in the middle i tried using sessions instead
I want to add array of integers to a session control i already tried using this code
$t=array(1,2,3,4,5);
$_SESSION['exam_id']=$t
I don't know if i can do such a thing or not but what is the parallels
What you specified is working correctly. Sessions can hold arrays.
The session superglobal is an represented as an array itself within PHP, so you can just get and set values by doing the following
Setting:
$_SESSION['exam_id'][] = "new value";
or
$_SESSION['exam_id'] = array("new value", "another value");
Getting:
$_SESSION['exam_id'][0]; // returns a value
This returns the first value in the exam_id array within the session variable
You will need to start the session. Make your code;
<?php
session_start();
$t = array(1,2,3,4,5);
$_SESSION['exam_id'] = $t;
You need session_start()
You didn't have a semi-colon ; at the end.
you can use array in session like this..
you have to start session with session_start();
and then store your array to session $_SESSION['items'][] = $item;
and then you use it, whenever you want:
foreach($_SESSION['items'][] as $item)
{
echo $item;
}
You can set PHP sessions equal to an array just like you're doing.
To set the $_SESSION variable equal to all POST data, you can do this:
$_SESSION['exam_id'] = $_POST;
Be sure to add session_start() prior to declaring any session variables.
$t=array(1,2,3,4,5);
$_SESSION['exam_id'] = array();
array_push($_SESSION['exam_id'],$t[0]);
array_push($_SESSION['exam_id'],$t[1]);
array_push($_SESSION['exam_id'],$t[2]);
array_push($_SESSION['exam_id'],$t[3]);
array_push($_SESSION['exam_id'],$t[4]);
Is it possible to ask for all data in my database and make objects from it and save it into an array or something, so I just need to call the database once and afterwards I just use my local array? If yes, how is it done?
public function getAllProjects(){
$query="SELECT * FROM projects";
$result=mysql_query($query);
$num=mysql_numrows($result);
while ($row = mysql_fetch_object($result)) {
// save object into array
}
}
public function fetchRow($row){
include("Project.php");
$project = new Project();
$id=$row->id;
$project->setId($id);
$title=$row->title;
$project->setTitle($title);
$infos=$row->info;
$project->setInfo($infos);
$text=$row->text;
$project->setText($text);
$cate=$row->category;
$project->setCategory($cate);
return $project;
}
If I have for example this code. How do i store the objects correctly into an array, where I grab the data from? And why can't I make more than one object of type "Project"?
Let's ignore the fact that you will run out of memory.
If you have everything in an array you will no longer have the functionalities of a relational database.
Try a search over a multi megabytes, multi dimensional array in php and be prepared for a extended coffee break.
If you are thinking in doing something like that is because you feel that the database is slow... You should learn about data normalization and correct use of indexes then.
And no NoSQL is not the answer.
Sorry to pop your balloon.
Edited to add: What you CAN to is use memcache to store the final product of some expensive processes. Don't bother storing the result of trivial queries, the internal cache of mysql is very optimized for those.
You should use the $_SESSION vars in php, To use them, add a session_start() at the beginning of your code. Then you can set vars with $_SESSION['selectaname'] = yourvar
Nothing prevent you to make a sql query like "SELECT username FROM users WHERE id = 1" and then set a $_SESSION['user'] = $queryresult
Then you'll have this :
echo $_SESSION['user'];
"mylogin"
how can i store an object in the $_GET array in PHP. i want to pass an object containing database information from one page to another page via the $_GET array, so there would be no need to access the database again.
To pass any sort of object, you'd have to serialize it on one end, and unserialize it on the other end.
But note that this will not work for database connections themselves : the connection to the database is automatically closed when a PHP script ends.
You could pass some connection informations, like login, host, or stuff like that (but that would not be a good idea -- quite not safe to expose such critical informations !) ; but you cannot pass a connection resource.
Really, you should be passing data from one page to another via the $_SESSION variable instead, if possible. That is what sessions are for. Ideally just store an id in the session and look up the data on each page. If you do use $_SESSION then it is as simple as ...
$_SESSION['myarray'] = $myarrayobject;
$_SESSION['someotherthing'] = 42;
If you have to use $_GET, then I would recommend just passing an id of some kind, then re-looking up the data on each page refesh.
Keep in mind, it would be easy for a malicious user to change the values that are sent via $_GET between pages, so make sure there is nothing that can be abused in this information.
You would need to serialize it to text (possibly using json_encode), then generate a URL that included it in the query string (making sure that it was urlencoded)
That's very bad idea.
Database were invented to serve each request, while query string were designed to pass only commands and identificators, not tons of data between browser and server
Instead of using get, another possibility to pass something from one page to another is to use the $_SESSION array and then to unset that variable on the other side whenever you're done with it. I've found that to be a pretty good way to do this.
Like everyone else has said though, passing database information can be a bad idea, assuming the information you're passing isn't something like username, first name, etc. If that's what you're passing when you say "database information" then I would store all that stuff in the $_SESSION variable and then destroy their session when they log out. Don't store the entire connection or something.
As has been said before you should avoid (mis-)using GET parameters as a "cache" for overly complex and loooong data.
On the other hand your question is vague enough to assume that you want to transmit only a few values. And your "second" script needs nothing else from the database, in fact it might not even have to check if those values came from a database at all.
In this case extract the values from your database result and append them as parameters to the url. Try to make the parameter list as simple as possible but yet unambiguous. http_build_query() can help you with that.
But keep in mind that you want to keep GET operations idempotent as described in http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html.
if ( isset($_GET['a'], $_GET['b'], $_GET['c']) ) {
// this doesn't care about the values in the database at all.
echo 'product: ', $_GET['a'] * $_GET['b'] * $_GET['c'], "\n";
}
else {
$pdo = new PDO("mysql:host=localhost;dbname=test", 'localonly', 'localonly');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// let's make it a self-contained example (and extra constly) by creating a temproary table ...
$pdo->exec('CREATE TEMPORARY TABLE foo (id int auto_increment, a int, b int, c int, primary key(id))');
// ... with some garbage data
$stmt = $pdo->prepare('INSERT INTO foo (a,b,c) VALUES (?,?,?)');
for($i=0; $i<10; $i++) {
$stmt->execute(array(rand(1,10), rand(1,10), rand(1,10)));
}
foreach( $pdo->query('SELECT a,b,c FROM foo', PDO::FETCH_ASSOC) as $row) {
printf('%s<br />',
http_build_query($row),
join(' * ', $row)
);
}
}
Using a user model which returns an array that looks like this:
$user_data['display_name'] = "John Doe";
$user_data['avatar'] = ./images/user144.jpg";
i create my session using $this->session->set_userdata('user_data',$user_data);
now if on another controller i let the user change his avatar,
how can i replace the session variable associated to that?
like $this->session->set_userdata('user_data["avatar"]',$new_avatar);
just wont work right?
hee thanks for the help...
From looking at an overview of your code, I'm guessing the best way to go about this is to unset the data and reset it.
Use $this->session->unset_userdata('thesessiontounset');
Then set it back up with the new information and old.
The session->set_userdata() function will only let you modify one key at a time. In your case the key refers to an array so what you're trying to do isn't possible in the way you're attempting to do it.
When I'm updating my session I run something like this.
//Create or setup the array of the fields you want to update.
$newFields = array('avatar' = > 'image01.png');
//Check to see if the session is currently populated.
if (!is_array($this->session->userdata('abc'))){
//...and if it's not - set it to a blank array
$this->session->set_userdata('abc',array());
}
//Retrieve the existing session data
$existing_session = $this->session->userdata('abc');
//Merge the existing data with the new data
$combined_data = array_merge($this->session->userdata('abc'), $newFields);
//update the session
$this->session->set_userdata('abc',$combined_data);
More details on array_merge can be found here
First controller
$user_data['display_name'] = "John Doe";
$user_data['avatar'] = "./images/user144.jpg";
$this->session->set_userdata('user_data',$user_data);
Second controller
$user_data = $this->session->userdata('user_data');
$user_data['avatar'] = $new_avatar;
$this->session->set_userdata('user_data', $new_avatar);
It is a bit late, but it might be useful to someone else, this seems to work:
$this->session->userdata['user_data']['avatar'] = $new_avatar;
$this->session->userdata['other_data']['other'] = $other;
$this->session->sess_write();
This allows you to edit values in array just like you do with $_SESION['user_data']['avatar'] = $avatar, with 'only' one extra line and only using CI library.
For Unset Session variable
$this->session->unset_userdata('avatar');
For Set Session variable
$this->session->set_userdata('avatar', '/images/user144.jpg"');
Use just like this
$this->session->set_userdata('session_var',"");