phrants.net
2Fév/100

PHP – Global Variables / Passing Variables to another page

I was at a total loss when trying to set a variable that I could use from one PHP page to another. The POST and GET functions worked to a point for the basic stuff, but I was quickly outgrowing the introductory course. I wanted to do something like an #include for each page, or to set a global variable that each individual page could access. It was extremely difficult to realize, but I finally figured out that what I wanted to do was to set a Session variable. As long as the session variable is set, you can use it at any time from any of your other PHP pages. This turned out to be incredibly easy:

session_start(); //this goes at the top of each page - it either creates or maintains a session with the server

$_SESSION['user_name']; //creates a session variable and can be assigned to a regular variable

$user_name = $_SESSION['user_name']; //now the 'local' variable is assigned from the 'global'

Session variables are amazing, you can just call on them from out of the blue and they will be there as long as the session is open. Sessions do expire after a prolonged period of time or if you close the browser or call on a PHP function to destroy it.  I had a great "Aha!" moment once I realized that I could assign a variable in one file and easily use it in any other PHP file. I guess this is what happens when you teach yourself PHP from online tutorials.

Taggé comme: , Aucun commentaire
2Fév/100

#1062 – Duplicate entry ‘1’ for key 1

This error kept popping up on me in myPhpAdmin while working with a mysql database. It was driving me up the wall as I didn't want to re-create the table just to assign a primary key and set auto-increment in an empty table. The first problem I noticed was that there was more than one "1" in the table. Makes sense, obviously you can't set the primary key in a column where there are duplicate entries. The second piece of the puzzle, however, was much more difficult to identify. It turns out that myPhpAdmin won't allow you to set auto_increment to a column where there is a "0" (zero) as unique key. I changed the zero to a 999 and then was able to set the auto increment. Then I went back in and manually changed the 999 back to zero. I couldn't find this solution anywhere else online, so I thought I would share it here.