Global variables question and a little bit of help needed

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
gijs
Forum Commoner
Posts: 53
Joined: Wed Aug 28, 2002 4:05 am
Location: Belgium

Global variables question and a little bit of help needed

Post by gijs »

Hi,
I'm learning since a couple of days a bit of php from a book called PHP Zonder Stress (Dutch for PHP without Stress). :wink:

Thanks to this section I figured out my problem.
Book examples were written in php 4.0.6 and I'm using 4.2.2
By turning the register_globals = On. The script in book works fine.

But I want to learn how to do it the right way.
So some help would be very much apreciated to convert the code to correct code for register_globals = Off.

Description:

In home.php there are articles listed, but limited to a display size of 40 characters. By clicking on the link "more" you go to the page news.php where the complete article is listed.

Code: Select all

<a href=nieuws/news.php?news_ID=" . $news&#1111;'news_ID'] . ">more</a>

In news.php with the following code and with register_globals = Off, I get an Notice: undifined variable $news_ID.

Code: Select all

// Performing the query where the news_ID is loaded into the variable $news_ID 
$news_SQL = "SELECT * FROM news WHERE news_ID='$news_ID'";

// Query results
$news_result = mysql_query($news_SQL) or die ("Error in query: $news_SQL. " . mysql_error());
$news = mysql_fetch_array($news_result);
Hoping someone could help me with this.

Thanks in advance,

Greetings from Belgium,

Gijs
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

User avatar
gijs
Forum Commoner
Posts: 53
Joined: Wed Aug 28, 2002 4:05 am
Location: Belgium

Post by gijs »

Thanks Mac,

I read it already before posting my problem.

As I'm completely new to php and programming in general I don't see the connextion.

Could you be more specific in order to help me ?

Thanks,

Gijs

P.S.: Sorry for my bad english.
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Basically you can't use $news_id as a variable, you have to refer to it using the $_GET array (because it's coming from the query string) so:

Code: Select all

$news_SQL = "SELECT * FROM news WHERE news_ID='$news_ID'";
should become

Code: Select all

$news_SQL = "SELECT * FROM news WHERE news_ID='".$_GET&#1111;'news_ID']."'";
Mac
User avatar
gijs
Forum Commoner
Posts: 53
Joined: Wed Aug 28, 2002 4:05 am
Location: Belgium

Post by gijs »

Thanks Mac,

Works fine with globals off.

Now trying to understand it: :?

1) I can't use $news_ID as avariable because basicly it doesn't exist in news.php

2) You use in this case $_get to extract the variable news_ID from the query string so it becomes defined.

Do I see this correctly ? Hope this doesn't sound to stupid.

Gijs
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

You've got it.

A bit more info -> With register_globals on if you send variables via a form, query string, cookie etc. you can just refer to this variable by the name you gave it ie. $news_id. However, with reg_globals off you need to be more explicit and use the special array generated for each type of data so if you send a variable via a form using the post method you would use $_POST['var_name'] (where var_name is the name you gave the variable). Accordingly for variables sent using the get method (ie. sent in the query string) you would use $_GET and for cookie's you would use $_COOKIE. The reason for this is to help you validate where user-inputted data has come from.

The pre-defined variables are listed here:
http://www.php.net/manual/en/language.v ... efined.php

Hope this isn't too convoluted to understand :) ,

Mac
User avatar
gijs
Forum Commoner
Posts: 53
Joined: Wed Aug 28, 2002 4:05 am
Location: Belgium

Post by gijs »

Thanks Mac,

I've been initially confused because $_get, $_post ect... where all in combination with forms.

I took it to the next fase where I tried to built a admin-section for the news articles.
So I creted a file news_list.php which lists all the articles.
Next to each article I created the same link as above, but refering to the file news_delete.php:

Code: Select all

<a href="news_delete.php?news_ID=<?php echo $news&#1111;'news_ID']; ?>">Delete  Article</a>
In the file news_delete.php I used the following code to delete the article:

Code: Select all

$news_SQL_del = "DELETE FROM news WHERE news_ID='".$_GET&#1111;'news_ID']."'";
$bool = mysql_query($news_SQL_del);
if($bool == 1) echo "<SCRIPT LANGUAGE=Javascript>window.alert('The article has been removed.')</script>";
if($bool <> 1) echo "<SCRIPT LANGUAGE=Javascript>window.alert('There has been an error.')</script>";
It works great, but I would like to take it up to another level !

I would like to achieve that, in stead of going to the file news_delete.php it is all done in the file news_list so that this file is immediately updated.
If that would work I could do the same thing for updating or adding the new_list.php.

I tought the following might do the tric, but I got it wrong somewhere down the line:

1) Making a link:

Code: Select all

<a href="news_delete.php?news_ID=<?php echo $news&#1111;'news_ID']; echo $action="delete"; ?>">Delete  Article</a>

2) Adding the following code:

Code: Select all

$action = array("delete", "insert", "update");
if($action == "delete") &#123;
//there has been clicked on the link, so delete record
$news_SQL_del = "DELETE FROM news WHERE news_ID='".$_GET&#1111;'news_ID']."'";
$bool = mysql_query($news_SQL_del);
if($bool == 1) echo "<SCRIPT LANGUAGE=Javascript>window.alert('The article has been removed.')</script>";
if($bool <> 1) echo "<SCRIPT LANGUAGE=Javascript>window.alert('There has been an error.')</script>";
&#125;
With the objective to add later on the actions for insert and update:

Code: Select all

if($action == "insert") &#123;
...
&#125;
if($action == "update") &#123;
...
&#125;

I think I went wrong either with the syntax of the link or the declaration of the variable $action. Of course it could be both aswell :?

Any advise ?

Thanks in advance,

Gijs

wrong with the variables
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

When you hover over the link what does it look like? Basically this:

Code: Select all

<a href="news_delete.php?news_ID=<?php echo $news&#1111;'news_ID']; echo $action="delete"; ?>">Delete  Article</a>
will just produce something like

Code: Select all

http://www.yoursite.com/news_delete.php?news_ID=2delete
you need to have something like:

Code: Select all

<a href="news_delete.php?news_ID=<?php echo $news&#1111;'news_ID']; ?>&action=<?php echo 'delete'; ?>">Delete  Article</a>
Then your link will look something like:

Code: Select all

http://www.yoursite.com/news_delete.php?news_ID=2&action=delete
You would then do your test for action something like this:

Code: Select all

if (isset($_GET&#1111;'action']) &#123; // to check that action is actually set 
                          // before trying to do anything with it
    switch ($_GET&#1111;'action']) &#123;
        case 'delete':
            // actions for when record to be deleted
            break;
        case 'update':
            // actions for when record to be updated
            break;
        case 'insert':
            // actions for when record to be inserted
            break;
        default:
           // actions for when $_GET&#1111;'action'] equal to none of the above
    &#125;
&#125; else &#123;
   // actions when $_GET&#1111;'action'] not set
&#125;
Hope this helps,

Mac
User avatar
gijs
Forum Commoner
Posts: 53
Joined: Wed Aug 28, 2002 4:05 am
Location: Belgium

Post by gijs »

Thanks again, Mac !

The though part is always the understanding of it all:

1) Hyperlink:
If the link consists of 2 parameters (news_ID and action) they are combined with an &.
What the parameters have to do is between <?php ... ; ?>
Do I see this correctly ?

2) To declinch the result of the hyperlink:
First you $_get the variable and check if the variable is set.
The control goes on with the nifty switch statement and depending on the value of the variable it executes a different piece of code.

3) Never the less I've changed it a little bit:

a) left out } else { and default because $action will only have 3 values.

b) used unset: because I don't need the variable anymore after performing the code.

c) Had a problem with the 'delete' code:
After the record was deleted the window.alert.box shows up with the message that the record was deleted, but on screen it was still visible.
To correct this I perform a query to get a fresh list of news articles.

So this is the code I ended up with:

Code: Select all

// to check that action is actually set before trying to do anything with it
if (isset($_GET&#1111;'action'])) &#123;
switch ($_GET&#1111;'action']) &#123;
	   		case 'delete':
			// The hyperlink action=delete has been clicked so, delete the record
			$news_SQL_del = "DELETE FROM news WHERE news_ID='".$_GET&#1111;'news_ID']."'";
			// Displaying a message depending on the outcome of the query
			$bool = mysql_query($news_SQL_del);
			if($bool == 1) echo "<SCRIPT LANGUAGE=Javascript>window.alert('The message has been deleted.')</script>";
			if($bool <> 1) echo "<SCRIPT LANGUAGE=Javascript>window.alert('There has been an error.')</script>";
			// Performing an update of the News List
			$news_SQL = "SELECT * FROM news ORDER BY news_datetime DESC";
			$news_result = mysql_query($news_SQL);
			// Kicking out the variable
			unset($_GET&#1111;'action']);
			// Stopping the switch statement
			break; 
			case 'update': 
			// actions for when record to be updated 
			break; 
			case 'insert': 
			// actions for when record to be inserted 
			break; 
		&#125; 
&#125;
It works ok. What do you think ?

By the way you almost got me fooled by leaving out the the second ) from (isset($_GET['action'])) :wink:

Regards,

Gijs
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

gijs wrote:1) Hyperlink:
If the link consists of 2 parameters (news_ID and action) they are combined with an &.
What the parameters have to do is between <?php ... ; ?>
Do I see this correctly ?
The different variables are separated by an ampersand (&) generally although ; is also used.
All you're doing between the PHP tags is echoing out some variables, you could echo out the whole thing like so:

Code: Select all

echo '<a href="news_delete.php?news_ID='.$news&#1111;'news_ID'].'&action='.$action.'>Delete  Article</a>';
gijs wrote:2) To declinch the result of the hyperlink:
First you $_get the variable and check if the variable is set.
The control goes on with the nifty switch statement and depending on the value of the variable it executes a different piece of code.
Exactly
gijs wrote:3) Never the less I've changed it a little bit:
Who said you could do that :wink:
gijs wrote:a) left out } else { and default because $action will only have 3 values.
Keeping the else might be a good plan as it will capture those times when action is not set. Someone could edit the query string to remove the action=delete bit and then you may want to display an error message.

Leaving in the default case in the switch statement is also a good idea as it handles the situation where one of your users decides to edit the query string to read action=notoneofyourthreethings.

However, I'm a big fan of building in as much error handling/user moronity checking as possible so I'd do these things but of course it's up to you what you're happy with.
gijs wrote:b) used unset: because I don't need the variable anymore after performing the code.
Fair enough.
gijs wrote:It works ok. What do you think ?
Nothing jumps out. It's always nice when things do what you want them to.
gijs wrote:By the way you almost got me fooled by leaving out the the second ) from (isset($_GET['action'])) :wink:
Ah, you spotted my evil trick :twisted:

Mac
User avatar
gijs
Forum Commoner
Posts: 53
Joined: Wed Aug 28, 2002 4:05 am
Location: Belgium

Post by gijs »

Thanks for your reply Mac,

First let me tell you I've added the else statement and default value in the switch as you suggested.
At this stage I use it as a control mechanism to better see where I go wrong.

} else {
echo "The varaible action is not set";
}

default :
echo "The default value for the switch statement";


I continued with my excersises and came across another variable problem:

I build a file called new_new.php. wich containes a form (left out rest of html)

Code: Select all

<form method="POST" action="news_list.php">
<input type="hidden" name="action" value="insert">
<input type="text" name="news_header"  size="58">
<input type="text" name="news_datetime" value="<?php echo date("Y-m-d H:i") ?>"size="19" maxlenght="19">
<textarea name="news_main" rows="10" cols="50"></textarea>
<input type="submit" name="submit" value="OK">
</form>
It send the data to news_list.php which containes the switch cases (delete, insert, update)

As the isset check was on $_GET and the form was based on $_POST, I've changed it into $_REQUEST, to cover them both.

Now I had to check if within action=insert the other variables from the form were known.
So in the switch for the case 'insert' I added another if(isset(variable)) as follows:

Code: Select all

// Checking if the other variables of the form are set
if (isset($_REQUEST&#1111;'news_main' and 'news_header' and 'news_datetime'])) &#123;

&#125; else &#123;
echo "The other variables are not set!";
&#125;
In syntaxis for the if(isset(...)) I got no errors.
But, after using the form in news_new.php it jumps to news_list.php, but doesn't add the new article.
It displays the normal article list and of course the result of else-statement: The other variables are not set!

Thanks to your tip of using the else-statement I now know that the other form variables are not set.

But were do I went wrong ?

Greetings,

Gijs
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Try this:

Code: Select all

if (isset($_POST&#1111;'news_main']) && isset($_POST&#1111;'news_header']) && isset($_POST&#1111;'news_datetime'])) &#123;
try to avoid using $_REQUEST, in fact just don't use it, use the array ($_POST, $_GET, $_SESSION, $_COOKIE whatever) that is most appropriate for the data being dealt with. The reason for doing this is to make sure that the data is coming from where you expect it to be coming from and not being entered by another means, ie. form data that should be posted being put in the query string by a user.

You went wrong with your isset statement in that each variable has to be tested separately and each array element must be referenced individually.

Mac
User avatar
gijs
Forum Commoner
Posts: 53
Joined: Wed Aug 28, 2002 4:05 am
Location: Belgium

Post by gijs »

Thanks again Mac,

Each time you give an answer you pose me another problem ! :roll:

Main problems were:

a) Not use $_REQUEST with to different methodes (GET & POST) for the variable action
b) Controlling if the varaible was set
c) Keeping the switch controle structure
d) Transfering the data contained by the variables from the forms into the database.

Here's the code I used to make it work:

Code: Select all

// to check that action is actually set before trying to do anything with it
if (isset($_GET&#1111;'action'])) &#123;
switch ($_GET&#1111;'action']) &#123;

	   		case 'delete':
			// The hyperlink action=delete has been clicked so, delete the record
			$news_SQL_del = "DELETE FROM news WHERE news_ID='".$_GET&#1111;'news_ID']."'";
			// Displaying a message depending on the outcome of the query
			$bool = mysql_query($news_SQL_del);
			if($bool == 1) echo "<SCRIPT LANGUAGE=Javascript>window.alert('The message has been deleted.')</script>";
			if($bool <> 1) echo "<SCRIPT LANGUAGE=Javascript>window.alert('There has been an error.')</script>";
			// Performing an update of the News List
			$news_SQL = "SELECT * FROM news ORDER BY news_datetime DESC";
			$news_result = mysql_query($news_SQL);
			// Kicking out the variable
			unset($_GET&#1111;'action']);
			// Stopping the switch statement
			break; 
	
			default :
			echo "The default value for the switch statement";
&#125;
&#125; elseif (isset($_POST&#1111;'action'])) &#123;
switch ($_POST&#1111;'action']) &#123;
	
			case 'insert':
			// Checking if the varaibles from form in news_new.php are set
			if (isset($_POST&#1111;'news_main']) && isset($_POST&#1111;'news_header']) && isset($_POST&#1111;'news_datetime'])) &#123; 
			// A new article has been send from news_new.php to news_list.php
			// Conversion of end_of_page-marks in news_main to HTML end_of_page-marks
			$_POST&#1111;'news_main'] = nl2br($_POST&#1111;'news_main']);
			$_POST&#1111;'news_main'] = eregi_replace("\n", "", $_POST&#1111;'news_main']);
			// Inserting the new record in the database
			$news_SQL_insert = "INSERT INTO news (news_header, news_datetime, news_main) 
			VALUES ('".$_POST&#1111;'news_header']."', '".$_POST&#1111;'news_datetime']."', '".$_POST&#1111;'news_main']."')";
			// Displaying a message depending on the outcome of the query
			$bool = mysql_query($news_SQL_insert);
			if($bool == 1) echo "<SCRIPT LANGUAGE=Javascript>window.alert('The message has been added.')</script>";
			if($bool <> 1) echo "<SCRIPT LANGUAGE=Javascript>window.alert('There has been an error.')</script>";
			// Performing an update of the News List
			$news_SQL = "SELECT * FROM news ORDER BY news_datetime DESC";
			$news_result = mysql_query($news_SQL);
			// Kicking out the variable
			unset($_POST&#1111;'action']);
			&#125; else &#123; 
   		  	// actions when $_POST&#1111;'action'] not set 
		  	echo "The variables for the form in news_new.php are not set";
			&#125;
			// Stopping the switch statement
			break;
						
			case 'update':
			// Checking if the varaibles from form in news_new.php are set
			if (isset($_POST&#1111;'news_main']) && isset($_POST&#1111;'news_header']) && isset($_POST&#1111;'news_datetime'])&& isset($_POST&#1111;'news_ID'])) &#123; 
			// A article has been updated and send from news_edit.php to news_list.php
			// Conversion of end_of_page-marks in news_main to HTML end_of_page-marks
			$_POST&#1111;'news_main'] = nl2br($_POST&#1111;'news_main']);
			$_POST&#1111;'news_main'] = eregi_replace("\n", "", $_POST&#1111;'news_main']);
			// Updating the record in the database
			$news_SQL_update = "UPDATE news SET news_header='".$_POST&#1111;'news_header']."', news_main='".$_POST&#1111;'news_main']."', news_datetime='".$_POST&#1111;'news_datetime']."' WHERE news_ID='".$_POST&#1111;'news_ID']."'";
			// Displaying a message depending on the outcome of the query
			$bool = mysql_query($news_SQL_update);
			if($bool == 1) echo "<SCRIPT LANGUAGE=Javascript>window.alert('The message has been updated.')</script>";
			if($bool <> 1) echo "<SCRIPT LANGUAGE=Javascript>window.alert('There has been an error.')</script>";
			// Performing an update of the News List
			$news_SQL = "SELECT * FROM news ORDER BY news_datetime DESC";
			$news_result = mysql_query($news_SQL);
			// Stopping the switch statement
			// Kicking out the variable
			unset($_POST&#1111;'action']);
			&#125; else &#123; 
   		  	// actions when $_POST&#1111;'action'] not set 
		  	echo "The variables for the form in news_edit.php are not set";
			&#125;
			// Stopping the switch statement
			break;
			
			default :
			echo "The default value for the switch statement";
&#125;
&#125; else &#123; 
// actions when $_GET&#1111;'action'] or $_POST&#1111;'action'] are not set 
// none defined for the moment !!!!
&#125;
Thanks to you Mac, I'm proud to say the whole 'basic' news article system works! :D

Completely with:
1) user:
a) a list with a small part (40 char) of the news article listed.
b) each limited article accessable through a link to display the full article.
2) Admin:
a) listing all the full articles.
b) deleting the articles individualy.
c) editing the articles individually.
d) inserting new articles.

Ok the code is without any doubt not the finest, but I'm making progress in learning php/mysql in only a couple of days and that is what its all about for me.
You know, at almost 40 the brain isn't what it used to be. :wink:

Cheers, gonna have a drink tonight.

Gijs
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Cool happy to help and glad you're getting somewhere with your script. It's nice to help someone who actually thinks about the answers.

Mac
Post Reply