p2p.wrox.com Forums

Need to download code?

View our list of code downloads.


  Return to Index  

beginning_php thread: Chapter 13: User Manager with register_globals = off


Message #1 by "Anton Vorster" <avorster@k...> on Fri, 13 Sep 2002 06:25:18
I'm stuck with trying to adapt the User Manager to work with 
register_globals = off.  I've managed to get the register.php and 
access_logger.php scripts to work without any problems. Has anybody 
succeeded in getting userman.php to work?  I'd really appreciate it if 
somebody could post the code.  Even the code for the User Viewer (Chapter 
12) will help.

Many thanks
Anton
Message #2 by "Nikolai Devereaux" <yomama@u...> on Fri, 13 Sep 2002 08:50:41 -0700
Hey Anton,

There's been a ton of posts on this (and other wrox PHP) lists about getting
the user viewer to work.

Basically, all you have to do is substitute any occurrence of $var with
$_XXX['var'], where XXX is either GET or POST, depending on how the
variables are being sent to the form.


If this isn't enough to help you solve the problem, feel free to reply with
a little more details about how/where the script is failing.

take care,

nik

Message #3 by "Anton Vorster" <avorster@k...> on Fri, 13 Sep 2002 19:46:59
Thanks for the reply, Nik!

Yes, I understand the principle of changing the variables to $_XXX
['var'].  In the case of this fairly complex script, I thought it would 
be easier to declare $var = $_GET['var'] at the beginning, rather than 
changing everything in the script itself.

With a lot of trial and error, I've gotten most of the script to work, 
but there are a couple of things still bothering me.

Here's my version of the script as it now stands:

<?php
//userman.php

include "./common_db.inc";

$link_id = db_connect();
mysql_select_db($default_dbname);
mysql_close($link_id);

function user_message($msg, $url='') {
  html_header();
  
  if(empty($url)) 
       echo "<SCRIPT>alert(\"$msg\");history.go(-1)</SCRIPT>";
  else echo "<SCRIPT>alert(\"$msg\");self.location.href='$url'</SCRIPT>";
  
  html_footer();
  exit;
}

function list_records() {
   global $default_dbname, $user_tablename;
   global $default_order_by, $records_per_page;

$default_sort_order = $_GET['default_sort_order'];
$sort_order = $_GET['sort_order'];
$order_by = $_GET['order_by'];
$cur_page = $_GET['cur_page'];
$PHP_SELF = $_SERVER['PHP_SELF']; 

   $link_id = db_connect($default_dbname);
   if(!$link_id) error_message(sql_error());

   $query = "SELECT count(*) FROM $user_tablename";

   $result = mysql_query($query);
   if(!$result) error_message(sql_error());
      
   $query_data = mysql_fetch_row($result);
   $total_num_user = $query_data[0];
   if(!$total_num_user) error_message('No User Found!');
   $page_num = $cur_page + 1;

   $total_num_page = $last_page_num 
                   = ceil($total_num_user/$records_per_page);
   
   html_header();
   
   echo "<CENTER><H3 class='heading'>$total_num_user users found. 
Displaying page
                     $page_num out of $last_page_num.</H3></CENTER>\n";
   
   if(empty($order_by)) {
      $order_by_str = "ORDER BY $default_order_by";
      $order_by = $default_order_by;
   }
   else $order_by_str = "ORDER BY $order_by";
   if(empty($sort_order)) {
      $sort_order_str = $org_sort_order = $default_sort_order;
      $sort_order = 'DESC';
   }
   else {
      $sort_order_str = $org_sort_order = $sort_order;
      if($sort_order == 'DESC') $sort_order = 'ASC';
      else $sort_order = 'DESC';
   }

   if(empty($cur_page)) {
      $cur_page = 0;
   }
     $limit_str = "LIMIT ". $cur_page * $records_per_page . 
                                     ", $records_per_page";
   $query = "SELECT usernumber, userid, userfirstname, userlastname FROM 
$user_tablename
                                  $order_by_str $sort_order_str 
$limit_str";
   
   $result = mysql_query($query);   
   if(!$result) error_message(sql_error());
?>
<DIV ALIGN="CENTER">
  <TABLE WIDTH="90%" BORDER="1" CELLPADDING="2" cellspacing="0" 
bordercolor="#FFFFFF" bgcolor="#99CCCC">
    <TR bgcolor="#009999">
      <TH WIDTH="10%" NOWRAP>
         <A class="default" HREF="<?php echo "$PHP_SELF?
action=list_records&sort_order=$sort_order&order_by=usernumber"; ?>">
         User No.
         </A>
      </TH>
      <TH WIDTH="25%" NOWRAP>
         <A class="default" HREF="<?php echo "$PHP_SELF?
action=list_records&sort_order=$sort_order&order_by=userid"; ?>">
         User ID
         </A>
      </TH>
      <TH WIDTH="25%" NOWRAP>
         <A class="default" HREF="<?php echo "$PHP_SELF?
action=list_records&sort_order=$sort_order&order_by=userfirstname"; ?>">
            First Name
         </A>
      </TH>
	  <TH WIDTH="25%" NOWRAP>
         <A class="default" HREF="<?php echo "$PHP_SELF?
action=list_records&sort_order=$sort_order&order_by=userlastname"; ?>">
            Last Name
         </A>
      </TH>
      <TH class="default" WIDTH="15%" NOWRAP>Action</TH>
   </TR>
<?php
   while($query_data = mysql_fetch_array($result)) {
      $usernumber = $query_data["usernumber"];
      $userid = $query_data["userid"];
      $userfirstname = $query_data["userfirstname"];
      $userlastname = $query_data["userlastname"];
      echo "<TR>\n";
      echo "<TD class=\"default\" WIDTH=\"10%\" 
ALIGN=\"CENTER\">$usernumber</TD>\n";
      echo "<TD class=\"default\" WIDTH=\"22%\" 
ALIGN=\"CENTER\">$userid</TD>\n";
      echo "<TD class=\"default\" WIDTH=\"22%\" 
ALIGN=\"CENTER\">$userfirstname</TD>\n";
      echo "<TD class=\"default\" WIDTH=\"22%\" 
ALIGN=\"CENTER\">$userlastname</TD>\n";
      echo "<TD class=\"default\" WIDTH=\"24%\" ALIGN=\"CENTER\">
            <A HREF=\"javascript:open_window('$PHP_SELF?
action=view_record&userid=$userid');\">View</A>&nbsp;    
            <A HREF=\"$PHP_SELF?action=delete_record&userid=$userid\" 
onClick=\"return confirm('Are you sure?');\">Delete</A></TD>\n";
      echo "</TR>\n";
   }
?>
</TABLE>
</DIV>
<?php      
   echo "<BR>\n";
   echo "<STRONG><CENTER>";
   if($page_num > 1) {
      $prev_page = $cur_page - 1;

      echo "<A class=\"default\" HREF=\"$PHP_SELF?
action=list_records&sort_order=$org_sort_order&order_by=$order_by&cur_page
=0\">[Top]</A>";

      echo "<A class=\"default\" HREF=\"$PHP_SELF?
action=list_records&sort_order=$org_sort_order&order_by=$order_by&cur_page
=$prev_page\">[Prev]</A>";
   }
   if($page_num <  $total_num_page) {
      $next_page = $cur_page + 1;
      $last_page = $total_num_page - 1;

      echo "<A class=\"default\" HREF=\"$PHP_SELF?
action=list_records&sort_order=$org_sort_order&order_by=$order_by&cur_page
=$next_page\">[Next]</A>";

      echo "<A class=\"default\" HREF=\"$PHP_SELF?
action=list_records&sort_order=$org_sort_order&order_by=$order_by&cur_page
=$last_page\">[Bottom]</A>";
   }

   echo "</STRONG></CENTER>"; 
   html_footer();
}

function delete_record() {
  global $default_dbname, $user_tablename, $access_log_tablename;
  $userid = $_GET['userid'];

  if(empty($userid)) error_message('Empty User ID!');
  
  $link_id = db_connect($default_dbname);
  if(!$link_id) error_message(sql_error());
  
  $query = "DELETE FROM $user_tablename WHERE userid = '$userid'";
  $result = mysql_query($query);
  if(!$result) error_message(sql_error());

  $num_rows = mysql_affected_rows($link_id);
  if($num_rows != 1) error_message("No such user: $userid");
  $query = "DELETE FROM $access_log_tablename WHERE userid = '$userid'";
  $result = mysql_query($query);
  
  user_message("All records regarding $userid have been trashed!");
}

function edit_record() {
    global $default_dbname, $user_tablename, $access_log_tablename;
	 
   $userid = $_GET['userid'];
   $new_userid = $_GET['new_userid'];
   $userfirstname = $_GET['userfirstname'];
   $userlastname = $_GET['userlastname'];
   $userpassword = $_GET['userpassword'];
   $useremail = $_GET['useremail'];
   $registerdate = $_GET['registerdate'];
   $lastaccesstime = $_GET['lastaccesstime'];
  
    if(empty($userid)) error_message('Empty User ID!');
  
  $link_id = db_connect($default_dbname);
  if(!$link_id) error_message(sql_error());
  
  $field_str = '';
  if($userid != $new_userid) $field_str = " userid = '$new_userid', ";
  if(!empty($userpassword)) {
    $field_str .= " userpassword = password('$userpassword') ";
  }
  $field_str .= " userfirstname = '$userfirstname', ";
  $field_str .= " userlastname = '$userlastname', ";
  $field_str .= " useremail = '$useremail', ";
  $field_str .= " registerdate = '$registerdate', ";
  $field_str .= " lastaccesstime = '$lastaccesstime' ";
  
  $query = "UPDATE $user_tablename SET $field_str WHERE userid 
= '$userid'";
  
  $result = mysql_query($query);
  if(!$result) error_message(sql_error());

  $num_rows = mysql_affected_rows($link_id);
  if(!$num_rows) error_message("Nothing changed!");
  if($userid != $new_userid) {
    $query = "UPDATE $access_log_tablename SET userid = '$new_userid' 
                                           WHERE userid = '$userid'";
    $result = mysql_query($query);
    if(!$result) error_message(sql_error());

    user_message("All records regarding $userid have been changed!", 
                 "$PHP_SELF?action=view_record&userid=$new_userid");
  }
  else {
    user_message("All records regarding $userid have been changed!");
  }
}

function edit_log_record() {
  global $default_dbname, $access_log_tablename;
  global $userid, $org_page, $new_page, $visitcount, $accessdate;

  if(empty($userid)) error_message('Empty User ID!');
  
  $link_id = db_connect($default_dbname);
  if(!$link_id) error_message(sql_error());
  
  $field_str = '';
    
  $field_str .= " page = '$new_page', ";
  $field_str .= " visitcount = $visitcount, ";
  $field_str .= " accessdate = '$accessdate' ";
  $query = "UPDATE $access_log_tablename SET $field_str 
                                         WHERE userid = '$userid'
                                         AND page = '$org_page'";
  $result = mysql_query($query);
  if(!$result) error_message(sql_error());
  $num_rows = mysql_affected_rows($link_id);
  if(!$num_rows) error_message("Nothing changed!");

  user_message("All records regarding $userid have been changed!");
}

function view_record() {

  global $default_dbname, $user_tablename, $access_log_tablename;
  $userid = $_GET['userid'];
  
  if(empty($userid)) error_message('Empty User ID!');
  
  $link_id = db_connect($default_dbname);
  
  if(!$link_id) error_message(sql_error());
  $query = "SELECT usernumber, userid, userfirstname, userlastname,
                   useremail, registerdate,
                   date_format(registerdate, '%M %e, %Y') 
                     as formatted_registerdate,
                   lastaccesstime, date_format(lastaccesstime, '%M %e, %Y 
%H:%i')
                     as formatted_lastaccesstime
                   FROM $user_tablename WHERE userid = '$userid'";
  $result = mysql_query($query);
  
  if(!$result) error_message(sql_error());
  $query_data = mysql_fetch_array($result);
  $usernumber = $query_data["usernumber"];
  $userid = $query_data["userid"];
  $userfirstname = $query_data["userfirstname"];
  $userlastname = $query_data["userlastname"];
  $useremail = $query_data["useremail"];
  $registerdate = $query_data["registerdate"];
  $formatted_registerdate = $query_data["formatted_registerdate"];
  $lastaccesstime = $query_data["lastaccesstime"];
  $formatted_lastaccesstime = $query_data["formatted_lastaccesstime"];
  
  html_header();
  echo "<CENTER><H3 class=\"heading\">
        Record for User No. $usernumber - $userid ($userfirstname 
$userlastname)
        </H3></CENTER>";
?>

<FORM METHOD="POST" ACTION="<?php echo $PHP_SELF; ?>">
<INPUT TYPE="HIDDEN" NAME="action" VALUE="edit_record">
<INPUT TYPE="HIDDEN" NAME="userid" VALUE="<? echo $userid; ?>">
<DIV ALIGN="CENTER"><CENTER>
      <TABLE WIDTH="90%" BORDER="1" CELLPADDING="2" cellspacing="0" 
bordercolor="#FFFFFF" bgcolor="#99CCCC">
        <TR>
          <TH class="default" WIDTH="30%" align="right" NOWRAP>User 
ID:</TH>
      <TD WIDTH="70%">
      <INPUT TYPE="TEXT" NAME="new_userid" 
                         VALUE="<?php echo $userid; ?>" 
                         SIZE="25" MAXLENGTH="25"></TD>
    </TR>
    <TR>
          <TH class="default" WIDTH="30%" align="right" NOWRAP>User 
Password:</TH>
      <TD WIDTH="70%"><INPUT TYPE="TEXT" NAME="userpassword" 
SIZE="25"></TD>
    </TR>
    <TR>
          <TH class="default" WIDTH="30%" align="right" NOWRAP>First 
Name:</TH>
      <TD WIDTH="70%"><INPUT TYPE="TEXT" NAME="userfirstname" 
                             VALUE="<?php echo $userfirstname; ?>" 
SIZE="25"></TD>
    </TR>
    <TR>
          <TH class="default" WIDTH="30%" align="right" NOWRAP>Last 
Name:</TH>
      <TD WIDTH="70%"><INPUT TYPE="TEXT" NAME="userlastname" 
                             VALUE="<?php echo $userlastname; ?>" 
SIZE="25"></TD>
    </TR>
    <TR>
          <TH class="default" WIDTH="30%" align="right" NOWRAP>Email:</TH>
      <TD WIDTH="70%"><INPUT TYPE="TEXT" NAME="useremail" SIZE="25"
                             VALUE="<?php echo $useremail; ?>"></TD>
    </TR>
    <TR>
          <TH class="default" WIDTH="30%" align="right" NOWRAP>Register 
Date:</TH>
      <TD class="default" WIDTH="70%">
        <INPUT TYPE="TEXT" NAME="registerdate" SIZE="10" MAXLENGTH="10" 
                           VALUE="<?php echo $registerdate; ?>">
						   <?php echo 
$formatted_registerdate;?>
      </TD>
    </TR>    
    <TR>
          <TH class="default" WIDTH="30%" align="right" NOWRAP>Last 
Access Time:</TH>
      <TD class="default" WIDTH="70%">
        <INPUT TYPE="TEXT" NAME="lastaccesstime" SIZE="14" MAXLENGTH="14" 
               VALUE="<?php echo $lastaccesstime; ?>">
        <?php echo $formatted_lastaccesstime; ?>
      </TD>
    </TR>    
    <TR>
      <TH WIDTH="100%" COLSPAN="2" NOWRAP>
        <INPUT TYPE="SUBMIT" VALUE="Change User Record">
        <INPUT TYPE="RESET" VALUE="Reset">
      </TH>
    </TR>
  </TABLE>
  </CENTER></DIV>
</FORM>
<?php 
  echo "<HR SIZE=\"2\" WIDTH=\"90%\">\n";
  $query = "SELECT page, visitcount, accessdate,
            date_format(accessdate, '%M %e, %Y %H:%i') as 
formatted_accessdate, score 
            FROM $access_log_tablename WHERE userid = '$userid'";
  $result = mysql_query($query);
  
  if(!$result) error_message(sql_error());
  if(!mysql_num_rows($result))
    echo "<CENTER class=\"default\"><b>No access log record for $userid 
($userfirstname $userlastname)</b></CENTER>";
  else {
    echo "<CENTER class=\"default\"><b>Access log record(s) for $userid 
($userfirstname $userlastname)</b></CENTER>";
?>
<DIV ALIGN="CENTER"><CENTER>
    <TABLE WIDTH="90%" BORDER="1" CELLPADDING="2" cellspacing="0" 
bordercolor="#FFFFFF" bgcolor="#99CCCC">
      <TR>
    <TH class="default" WIDTH="20%" NOWRAP>Page</TH>
    <TH class="default" WIDTH="10%" NOWRAP>Hits</TH>
    <TH class="default" WIDTH="30%" NOWRAP>Last Access</TH>
	<TH class="default" WIDTH="10%" NOWRAP>Score</TH>
    <TH class="default" WIDTH="30%" NOWRAP>Action</TH>
  </TR>
<?php    
    while($query_data = mysql_fetch_array($result)) {
      $page = $query_data["page"];
      $visitcount = $query_data["visitcount"];
      $accessdate = $query_data["accessdate"];
      $formatted_accessdate = $query_data["formatted_accessdate"];
      $score = $query_data["score"];
      
      echo "<FORM METHOD=\"POST\" ACTION=\$PHP_SELF\">";
      echo "<INPUT TYPE=\"HIDDEN\" NAME=\"action\"
                                   VALUE=\"edit_log_record\">";
      echo "<INPUT TYPE=\"HIDDEN\" NAME=\"userid\" VALUE=\"$userid\">";
      echo "<INPUT TYPE=\"HIDDEN\" NAME=\"org_page\" VALUE=\"$page\">";
      echo "<TR>\n";
      echo "<TD WIDTH=\"20%\"><INPUT TYPE=\"TEXT\"
                NAME=\"new_page\" SIZE=\"30\" VALUE=\"$page\"></TD>\n";
      echo "<TD WIDTH=\"10%\" ALIGN=\"CENTER\">
              <INPUT TYPE=\"TEXT\" NAME=\"visitcount\" SIZE=\"3\" 
                                   VALUE=\"$visitcount\"></TD>\n";
      echo "<TD WIDTH=\"30%\" ALIGN=\"CENTER\">
              <INPUT TYPE=\"TEXT\" NAME=\"accessdate\" SIZE=\"14\" 
                     MAXLENGTH=\"14\" VALUE=\"$accessdate\">
            <div class=\"default\">$formatted_accessdate</div></TD>\n";
      echo "<TD WIDTH=\"10%\" ALIGN=\"CENTER\">
              <INPUT TYPE=\"TEXT\" NAME=\"score\" SIZE=\"3\" 
                                   VALUE=\"$score\"></TD>\n";
      echo "<TD WIDTH=\"30%\" ALIGN=\"CENTER\">
              <INPUT TYPE=\"SUBMIT\" VALUE=\"Change\">
              <INPUT TYPE=\"RESET\" VALUE=\"Reset\"></TD>\n";
      echo "</TR>\n";
      echo "</FORM>\n";
    }
?>
  </TR>
</TABLE>
</CENTER></DIV>
<?php  
  }
  html_footer();
}

switch($_GET['action']) {
  case "edit_record":
    edit_record();
  break;
  case "edit_log_record":
    edit_log_record();
  break;
  case "delete_record":
    delete_record();
  break;
  case "view_record":
    view_record();
  break;
  default: 
    list_records();
  break;

}
?>

The first thing I don't understand, is why the script would not work with 
all the global variables being declared in the new format.  In the case 
of some variables, I had to revert back to "global $var".  This applies, 
for instance, to $default_dbname and $user_tablename under function 
list_records() and function delete_record.

But at least I got those functions to work...

I haven't, however, been able to get edit_record to work.  When I try and 
edit a record, it simply changes back to its original value.

I haven't yet tried to modify edit_log_record.

Any help in understanding what's going on and getting this script fully 
functional, will be much appreciated!

Many thanks,
Anton
Message #4 by "Nikolai Devereaux" <yomama@u...> on Fri, 13 Sep 2002 15:47:53 -0700
> Yes, I understand the principle of changing the variables to $_XXX
> ['var'].  In the case of this fairly complex script, I thought it would
> be easier to declare $var = $_GET['var'] at the beginning, rather than
> changing everything in the script itself.

Be careful, though -- what you're doing is just a long-winded way around
register_globals.  If this is indeed your intention, use the extract()
function:

http://www.php.net/extract

for example:

<?php

extract($_GET);

echo $var;
?>


> With a lot of trial and error, I've gotten most of the script to work,
> but there are a couple of things still bothering me.
>
> Here's my version of the script as it now stands:

  <HUGE snip>

> The first thing I don't understand, is why the script would not work with
> all the global variables being declared in the new format.  In the case
> of some variables, I had to revert back to "global $var".  This applies,
> for instance, to $default_dbname and $user_tablename under function
> list_records() and function delete_record.

I doubt very highly that your dbname and tablenames are passed as GET
parameters to your script.  When you declare a variable in global scope,
it's a global var.  This means that if you want to access it inside any
function's scope, you'll need to import it using the global keyword or via
the $GLOBALS array.

For instance, if you were to call foo.php?username=nikolai

and this was foo.php:

<?php

$admin_username = 'nikolai';

function is_admin()
{
   global $admin_username;
   return ($admin_username == $_GET['username']);
}

// or this:

function is_admin()
{
   return ($GLOBALS['admin_username'] == $_GET['username']);
}


> But at least I got those functions to work...
>
> I haven't, however, been able to get edit_record to work.  When I try and
> edit a record, it simply changes back to its original value.
>
> I haven't yet tried to modify edit_log_record.
>
> Any help in understanding what's going on and getting this script fully
> functional, will be much appreciated!

To be honest, there's far too much code in the userview for me to read
through -- I'm much too busy.  I will say one thing:  If you can get things
to work using the global keyword, then you must also be able to get things
to work without it.  You're most likely confusing where the variables are
originally defined.

With register_globals = On, PHP __copies__ all the index names and values
from the superglobal arrays into global scope.

That means that you're not dealing with the original, which is important.
Also, when you assign $foo = $_GET['foo'];, $foo is also a COPY of
$_GET['foo'], not the original.

The consequence of this is when you modify $foo, $_GET['foo'] is unchanged.

If you have several functions, then, with all use $_GET['foo'] via some
local variable assignment, then any changes you make in one function are NOT
available to the rest of them.


What this also means is that any script you can get working by creating
local or global copies of the $_GET parameters MUST also work by accessing
the variables from within the $_GET array directly.


Hope this all helps!

Nik

Message #5 by "Anton Vorster" <avorster@k...> on Sat, 14 Sep 2002 01:35:56 +0200
Thanks Again, Nik

I *thought* I had a fair understanding of what was going on, but I clearly
need to brush up on my theory...

----- Original Message -----
From: "Nikolai Devereaux" <yomama@u...>
To: "beginning php" <beginning_php@p...>
Sent: Saturday, September 14, 2002 12:47 AM
Subject: [beginning_php] RE: Chapter 13: User Manager with register_globals
= off


>
> > Yes, I understand the principle of changing the variables to $_XXX
> > ['var'].  In the case of this fairly complex script, I thought it would
> > be easier to declare $var = $_GET['var'] at the beginning, rather than
> > changing everything in the script itself.
>
> Be careful, though -- what you're doing is just a long-winded way around
> register_globals.  If this is indeed your intention, use the extract()
> function:
>
> http://www.php.net/extract
>
> for example:
>
> <?php
>
> extract($_GET);
>
> echo $var;
> ?>
>
>
> > With a lot of trial and error, I've gotten most of the script to work,
> > but there are a couple of things still bothering me.
> >
> > Here's my version of the script as it now stands:
>
>   <HUGE snip>
>
> > The first thing I don't understand, is why the script would not work
with
> > all the global variables being declared in the new format.  In the case
> > of some variables, I had to revert back to "global $var".  This applies,
> > for instance, to $default_dbname and $user_tablename under function
> > list_records() and function delete_record.
>
> I doubt very highly that your dbname and tablenames are passed as GET
> parameters to your script.  When you declare a variable in global scope,
> it's a global var.  This means that if you want to access it inside any
> function's scope, you'll need to import it using the global keyword or via
> the $GLOBALS array.
>
> For instance, if you were to call foo.php?username=nikolai
>
> and this was foo.php:
>
> <?php
>
> $admin_username = 'nikolai';
>
> function is_admin()
> {
>    global $admin_username;
>    return ($admin_username == $_GET['username']);
> }
>
> // or this:
>
> function is_admin()
> {
>    return ($GLOBALS['admin_username'] == $_GET['username']);
> }
>
>
> > But at least I got those functions to work...
> >
> > I haven't, however, been able to get edit_record to work.  When I try
and
> > edit a record, it simply changes back to its original value.
> >
> > I haven't yet tried to modify edit_log_record.
> >
> > Any help in understanding what's going on and getting this script fully
> > functional, will be much appreciated!
>
> To be honest, there's far too much code in the userview for me to read
> through -- I'm much too busy.  I will say one thing:  If you can get
things
> to work using the global keyword, then you must also be able to get things
> to work without it.  You're most likely confusing where the variables are
> originally defined.
>
> With register_globals = On, PHP __copies__ all the index names and values
> from the superglobal arrays into global scope.
>
> That means that you're not dealing with the original, which is important.
> Also, when you assign $foo = $_GET['foo'];, $foo is also a COPY of
> $_GET['foo'], not the original.
>
> The consequence of this is when you modify $foo, $_GET['foo'] is
unchanged.
>
> If you have several functions, then, with all use $_GET['foo'] via some
> local variable assignment, then any changes you make in one function are
NOT
> available to the rest of them.
>
>
> What this also means is that any script you can get working by creating
> local or global copies of the $_GET parameters MUST also work by accessing
> the variables from within the $_GET array directly.
>
>
> Hope this all helps!
>
> Nik
>
>
>

Message #6 by "Anton Vorster" <avorster@k...> on Sat, 14 Sep 2002 08:18:22
Okay, for now I've made things easy for myself by adding the following 
code to the top of the script:

if (!empty($_GET)) {
extract($_GET);
} else if (!empty($HTTP_GET_VARS)) {
extract($HTTP_GET_VARS);
}

if (!empty($_POST)) {
extract($_POST);
} else if (!empty($HTTP_POST_VARS)) {
extract($HTTP_POST_VARS);
}

Everything works fine, except for the following bit:

function edit_log_record() {
  global $default_dbname, $access_log_tablename;
  global $userid, $org_page, $new_page, $visitcount, $accessdate, $score;

  if(empty($userid)) error_message('Empty User ID!');
  
  $link_id = db_connect($default_dbname);
  if(!$link_id) error_message(sql_error());

  $field_str = '';
    
  $field_str .= " page = '$new_page', ";
  $field_str .= " visitcount = $visitcount, ";
  $field_str .= " accessdate = '$accessdate,' ";
  $field_str .= " score = $score ";
  $query = "UPDATE $access_log_tablename SET $field_str 
                                         WHERE userid = '$userid'
                                         AND page = '$org_page'";
  $result = mysql_query($query);
  if(!$result) error_message(sql_error());
  $num_rows = mysql_affected_rows($link_id);
  if(!$num_rows) error_message("Nothing changed!");

  user_message("All records regarding $userid have been changed!");
}

I've added the row "score" to the original database and modified the 
script accordingly. If I comment out the line 

     $field_str .= " score = $score ";

everything works perfectly -- I am able to edit the values in the log 
record (except for $score, of course).  But the script breaks as soon as 
I try and implement the above line.  I then only get a blank page after 
clicking on "Change".

Any suggestions, PLEASE??

(Nik, I promise not to bother you again for a while if you can help me 
out here...)
Message #7 by "Nikolai Devereaux" <yomama@u...> on Mon, 16 Sep 2002 10:52:51 -0700
First things first:

> (Nik, I promise not to bother you again for a while if you can help me
> out here...)

I'm not bothered by your questions!

Now then -- when you're getting a blank page, I wonder if it's because your
error_reporting setting in php.ini is preventing your errors from being
displayed...  What's error_message() and sql_error()?

Anyway, here's some guesses.

$score isn't wrapped in single quotes in your query.  Change the line

 $field_str .= "score .= $score";
    to
 $field_str .= "score .= '$score'";


Are you sure that your form input field name is score?  There's no typos,
it's not "user_score" or anything like that?

Are you passing a score that's compatible with the data type of the score
column in the database?  i.e.  you're not passing "Good" when the column
data type is "INTEGER", or something like that?


Take care,

Nik

Message #8 by "Anton Vorster" <avorster@k...> on Mon, 16 Sep 2002 22:52:32 +0200
> $score isn't wrapped in single quotes in your query.  Change the line
>
>  $field_str .= "score .= $score";
>     to
>  $field_str .= "score .= '$score'";

Done that.  Didn't help.

> Are you sure that your form input field name is score?  There's no typos,
> it's not "user_score" or anything like that?

Checked that.  The form input field name is score.

> Are you passing a score that's compatible with the data type of the score
> column in the database?  i.e.  you're not passing "Good" when the column
> data type is "INTEGER", or something like that?
>
The data type is mediumint(5).  I tried using the form to change the value
from 0 (the default value) to 5.

When I uncomment the line

    $field_str .= "score .= '$score'";

it breaks the whole script -- I can't change any of the values on the form.
On submit, I just get a blank page.

Oh, and I set error reporting to E_ALL.  I still just get a blank page -- no
error messages!

Any other ideas???  This is driving me crazy...

Many thanks,
Anton

Message #9 by Michael Belanger <Michael.Belanger@p...> on Mon, 16 Sep 2002 14:02:42 -0700

-----Original Message-----
From: Anton Vorster [mailto:avorster@k...]
Sent: Monday, September 16, 2002 1:53 PM
To: beginning php
Subject: [beginning_php] RE: Chapter 13: User Manager with
register_globals = off

> $score isn't wrapped in single quotes in your query.  Change the line
>
>  $field_str .= "score .= $score";
>     to
>  $field_str .= "score .= '$score'";

Done that.  Didn't help.

> Are you sure that your form input field name is score?  There's no typos,
> it's not "user_score" or anything like that?

When I uncomment the line

    $field_str .= "score .= '$score'";

humm..  That line looks weird to me.  Why wouldn't you write it this way?

	$field_str .= "score .= \'$score\'";

		-or-

	$field_str .= "score" .= $score;

??

<back to lurking>

-M


PLEASE NOTE: This message, including any attachments, may include
privileged, confidential and/or inside information. Any distribution or use
of this communication by anyone other than the intended recipient(s) is
strictly prohibited and may be unlawful. If you are not the intended
recipient, please notify the sender by replying to this message and then
delete it from your system. Thank you.


Message #10 by "Nikolai Devereaux" <yomama@u...> on Mon, 16 Sep 2002 14:20:03 -0700
One more idea --

try outputting a bunch of debugging statements up to and after the actual
database query.  What is your error_message() defined to be?  Does it output
text to the client directly, or buffer it at all?  Does it exit the script,
or does the script continue execution?


<?php

function printr($var, $desc = '')
{
  echo "<PRE>";
  if($desc != '')
    echo "$desc: ";
  print_r($var);
  echo "</PRE>\n";
}

if (!empty($_GET)) {
  printr($_GET, '$_GET');
  extract($_GET);
}
// don't need the elseif, if you're running
// php > 4.1.0, $HTTP_GET_VARS will not be set
// unless $_GET is, too.


if (!empty($_POST))
{
  printr($_POST, '$_POST');
  extract($_POST);
}


   ...

function edit_log_record() {
  global $default_dbname, $access_log_tablename;
  global $userid, $org_page, $new_page, $visitcount, $accessdate, $score;

  if(empty($userid)) error_message('Empty User ID!');

  $link_id = db_connect($default_dbname);
  if(!$link_id) error_message(sql_error());

  $field_str = '';

  $field_str .= " page = '$new_page', ";
  $field_str .= " visitcount = $visitcount, ";
  $field_str .= " accessdate = '$accessdate,' ";
  $field_str .= " score = $score ";
  $query = "UPDATE $access_log_tablename SET $field_str
                                         WHERE userid = '$userid'
                                         AND page = '$org_page'";

  printr($query, '$query');

  $result = mysql_query($query);

  printr($result, '$result');

  if(!$result) error_message(sql_error());
  $num_rows = mysql_affected_rows($link_id);
  if(!$num_rows) error_message("Nothing changed!");

  user_message("All records regarding $userid have been changed!");
}



take care,

nik

Message #11 by "Nikolai Devereaux" <yomama@u...> on Mon, 16 Sep 2002 14:43:55 -0700
> humm..  That line looks weird to me.  Why wouldn't you write it this way?
>
> 	$field_str .= "score .= \'$score\'";

Because it's unnecessary.  the single-quote character isn't anything special
inside a double-quoted string.  It can't terminate the string.

Only the quote character used to START a string can end it; therefore,
within a double quoted string, you'd have to escape double quotes inside the
string.

Examples:

echo "\"Hello\", Nik said.";
echo 'Jake looked up.  "Hello, yourself."';

echo 'Nik couldn\'t help but think...';
echo "'sounds like someone has a case of the Mondays.'";


make sense?


Nik

  http://www.php.net/types.string

Message #12 by "Anton Vorster" <avorster@k...> on Tue, 17 Sep 2002 01:09:54 +0200
Great, I've implemented the debugging script and there are no errors, the
script seems to do what it's supposed to:

  $_POST: Array
(
    [action] => edit_log_record
    [userid] => akav
    [org_page] => /UserMan/test.php
    [new_page] => /UserMan/test.php
    [visitcount] => 9
    [score] => 10
)

Turns out it's a MySQL error.  In the common_db.inc file, there are the
following lines:

    $MYSQL_ERRNO = '';
    $MYSQL_ERROR = '';

 which I guess accounts for the blank page.  So I changed the second line
to:

  $MYSQL_ERROR = 'MySQL Error';

which results in an error message 'MySQL Error' popping up when I execute
the script.

Now what on earth could the MySQL error be???


----- Original Message -----
From: "Nikolai Devereaux" <yomama@u...>
To: "beginning php" <beginning_php@p...>
Sent: Monday, September 16, 2002 11:20 PM
Subject: [beginning_php] RE: Chapter 13: User Manager with register_globals
= off


>
> One more idea --
>
> try outputting a bunch of debugging statements up to and after the actual
> database query.  What is your error_message() defined to be?  Does it
output
> text to the client directly, or buffer it at all?  Does it exit the
script,
> or does the script continue execution?
>
>
> <?php
>
> function printr($var, $desc = '')
> {
>   echo "<PRE>";
>   if($desc != '')
>     echo "$desc: ";
>   print_r($var);
>   echo "</PRE>\n";
> }
>
> if (!empty($_GET)) {
>   printr($_GET, '$_GET');
>   extract($_GET);
> }
> // don't need the elseif, if you're running
> // php > 4.1.0, $HTTP_GET_VARS will not be set
> // unless $_GET is, too.
>
>
> if (!empty($_POST))
> {
>   printr($_POST, '$_POST');
>   extract($_POST);
> }
>
>
>    ...
>
> function edit_log_record() {
>   global $default_dbname, $access_log_tablename;
>   global $userid, $org_page, $new_page, $visitcount, $accessdate, $score;
>
>   if(empty($userid)) error_message('Empty User ID!');
>
>   $link_id = db_connect($default_dbname);
>   if(!$link_id) error_message(sql_error());
>
>   $field_str = '';
>
>   $field_str .= " page = '$new_page', ";
>   $field_str .= " visitcount = $visitcount, ";
>   $field_str .= " accessdate = '$accessdate,' ";
>   $field_str .= " score = $score ";
>   $query = "UPDATE $access_log_tablename SET $field_str
>                                          WHERE userid = '$userid'
>                                          AND page = '$org_page'";
>
>   printr($query, '$query');
>
>   $result = mysql_query($query);
>
>   printr($result, '$result');
>
>   if(!$result) error_message(sql_error());
>   $num_rows = mysql_affected_rows($link_id);
>   if(!$num_rows) error_message("Nothing changed!");
>
>   user_message("All records regarding $userid have been changed!");
> }
>
>
>
> take care,
>
> nik
>
>
>

Message #13 by "Nikolai Devereaux" <yomama@u...> on Mon, 16 Sep 2002 16:24:20 -0700
> Turns out it's a MySQL error.  In the common_db.inc file, there are the
> following lines:
>
>     $MYSQL_ERRNO = '';
>     $MYSQL_ERROR = '';
>
>  which I guess accounts for the blank page.  So I changed the second line
> to:
>
>   $MYSQL_ERROR = 'MySQL Error';
>
> which results in an error message 'MySQL Error' popping up when I execute
> the script.
>
> Now what on earth could the MySQL error be???


Again, what are error_message() and sql_error() defined to be??  I think
I've asked this in most (if not all) of my replies!


There are two built-in PHP functions, mysql_error() and mysql_errno() that
can be called to get the most recent mysql error message and error number,
respectively (if any).

Keeping a global variable around to hold these values is a recipe for bugs
(as you by now have learned.)

sql_error() should do nothing more than wrap a call to mysql_error().

It's my guess, after reading your posts, that sql_error is nothing more than
something like this:

function sql_error()
{
  global $MYSQL_ERROR, $MYSQL_ERRNO;
  return 'MySQL error! (' . $MYSQL_ERRNO . ') ' . $MYSQL_ERROR;
}


This should, of course, be more like this:

function sql_error()
{
  return 'MySQL error! (' . mysql_errno(). ') ' . mysql_error();
}

take care,

Nik

Message #14 by "Anton Vorster" <avorster@k...> on Tue, 17 Sep 2002 10:05:05 +0200
> Again, what are error_message() and sql_error() defined to be??  I think
> I've asked this in most (if not all) of my replies!

Sorry, I was confused. I thought I had answered this.  Sql_error() and
error_message($msg) are defined as follows in common_db.inc:

function sql_error() {
   global $MYSQL_ERRNO, $MYSQL_ERROR;

   if(empty($MYSQL_ERROR)) {
      $MYSQL_ERRNO = mysql_errno();
      $MYSQL_ERROR = mysql_error();
   }
   return "$MYSQL_ERRNO: $MYSQL_ERROR";
}

function error_message($msg) {
   html_header();
   echo "<SCRIPT>alert(\"Error: $msg\");history.go(-1)</SCRIPT>";
   html_footer();
   exit;
}

Does this shed any light on the problem?

Thanks again,
Anton

Message #15 by "Nikolai Devereaux" <yomama@u...> on Tue, 17 Sep 2002 09:29:03 -0700
Yes, this clears some things up.

> function sql_error() {
>    global $MYSQL_ERRNO, $MYSQL_ERROR;
>
>    if(empty($MYSQL_ERROR)) {
>       $MYSQL_ERRNO = mysql_errno();
>       $MYSQL_ERROR = mysql_error();
>    }
>    return "$MYSQL_ERRNO: $MYSQL_ERROR";
> }


if $MYSQL_ERROR is NOT empty, then you'll never overwrite it's value with
the new error returned by mysql_error()!

You should get rid of the $MYSQL_ERROR and $MYSQL_ERRNO variables entirely.

function sql_error()
{
   return mysql_errno() . ': ' . mysql_error();
}


As for the error_message(), I don't like that error_message() outputs an
entire HTML page with just some javascript in it... have you viewed the
source of your pages?  Is there anything there?

For the time being, why not do this:

function error_message($msg)
{
  exit('<B>ERROR!</B> ' . $msg);
}

Javascript alerts (or any modal popup window, for that matter) get REALLY
annoying, REALLY quickly, when used as a debugging tool.


Take care,

nik

Message #16 by "Anton Vorster" <avorster@k...> on Tue, 17 Sep 2002 19:35:15
HOW COULD I BE THIS BLIND????!!!!

I just realized that the following line:

   $field_str .= " accessdate = '$accessdate,' ";

should of course have been:

  $field_str .= " accessdate = '$accessdate', ";


Now everything works perfectly.

Nik - many, many, many thanks for your patience and your willingness to 
help a bumbling PHP beginner.

When can I expect your bill?

Regards,
Anton
Message #17 by "Nikolai Devereaux" <yomama@u...> on Tue, 17 Sep 2002 12:10:19 -0700
I completely missed it, too...  That it was "working" without the last line
in the where clause made me wonder, since there would've been a trailing
comma, but I had just assumed (and we all know what they say about assuming
things) that you had added and removed the comma as necessary.


> When can I expect your bill?

If only...  =)


Take care,

Nik


  Return to Index