Jump to content
Larry Ullman's Book Forums

Recommended Posts

New to this forum. Have been playing around with PHP and MySQL for some time and now writing my first application. So far all seems to be working but have got to chapter 8, script 8.4 edit_user.php (accessed from view_users.php) and will not seem to work.

 

The edit link from view_users.php works and will display the record (can be seen at adrianball.london/view_users.php)

 

Record information can be changed in the form but, after submitting the form, the database is not updated and the latest information does not display.

 

My script code is below which I have checked 3 times with the book. Any help appreciated.

 

Many thanks.

 

<?php # Script 8.4 - edit_user.php

 
// This page edits a user.
// This page is accessed through view_users.php.
 
$page_title = 'Edit a User';
include ('./includes/header.html');
 
// Check for a valid user ID, through GET or POST.
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // Accessed through view_users.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form has been submitted.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<h1 id="mainhead">Page Error</h1>
<p class="error">This page has been accessed in error.</p><p><br /><br /></p>';
include ('./includes/footer.html'); 
exit();
}
 
require_once ('../mysql_connect.php'); // Connect to the db.
 
// Check if the form has been submitted.
if (isset($_POST['submitted'])) {
 
$errors = array(); // Initialize error array.
 
// Check for a first name.
if (empty($_POST['firstname'])) {
$errors[] = 'You forgot to enter your first name.';
} else {
$fn = escape_data($_POST['firstname']);
}
 
// Check for a last name.
if (empty($_POST['lastname'])) {
$errors[] = 'You forgot to enter your last name.';
} else {
$ln = escape_data($_POST['lastname']);
}
 
// Check for an email address.
if (empty($_POST['email'])) {
$errors[] = 'You forgot to enter your email address.';
} else {
$e = escape_data($_POST['email']);
}
 
if (empty($errors)) { // If everything's OK.
 
//  Test for unique email address.
$query = "SELECT user_id FROM students WHERE email='$e' AND user_id != $id";
$result = mysql_query($query);
if (mysql_num_rows($result) == 0) {
 
// Make the query.
$query = "UPDATE students SET firstname='$fn', lastname='$ln', email='$e' WHERE user_id=$id";
$result = @mysql_query ($query); // Run the query.
if (mysql_affected_rows() == 1) { // If it ran OK.
 
// Print a message.
echo '<h1 id="mainhead">Edit a User</h1>
<p>The user has been edited.</p><p><br /><br /></p>';
 
} else { // If it did not run OK.
echo '<h1 id="mainhead">System Error</h1>
<p class="error">The user could not be edited due to a system error. We apologize for any inconvenience.</p>'; // Public message.
echo '<p>' . mysql_error() . '<br /><br />Query: ' . $query . '</p>'; // Debugging message.
include ('./includes/footer.html'); 
exit();
}
 
} else { // Already registered.
echo '<h1 id="mainhead">Error!</h1>
<p class="error">The email address has already been registered.</p>';
}
 
} else { // Report the errors.
 
echo '<h1 id="mainhead">Error!</h1>
<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p><p><br /></p>';
 
} // End of if (empty($errors)) IF.
 
} // End of submit conditional.
 
// Always show the form.
 
// Retrieve the users information.
$query = "SELECT firstname, lastname, email FROM students WHERE user_id=$id";
$result = @mysql_query ($query); // Run the query.
 
if (mysql_num_rows($result) == 1) { // Valid user ID, show the form.
 
// Get the user's information.
$row = mysql_fetch_array ($result, MYSQL_NUM);
 
// Create the form.
echo '<h2>Edit a User</h2>
<form action="edit_user.php" method="post">
<p>First Name: <input type="text" name="firstname" size="15" maxlength="15" value="' .  $row[0] . '" /></p>
<p>Last Name: <input type="text" name="lastname" size="15" maxlength="30" value="' .  $row[1] . '" /></p>
<p>Email Address: <input type="text" name="email" size="20" maxlength="40" value="' .  $row[2] . '"  /> </p>
<p><input type="submit" name="submit" value="Submit" /></p>
<input type="hidden" name="submitted" value="TRUE" />
<input type="hidden" name="id" value="' . $id . '" />
</form>';
 
} else { // Not a valid user ID.
echo '<h1 id="mainhead">Page Error</h1>
<p class="error">This page has been accessed in error.</p><p><br /><br /></p>';
}
 
mysql_close(); // Close the database connection.
 
include ('./includes/footer.html');
?>

Share this post


Link to post
Share on other sites

Hello and welcome to the forums.

 

Obviously, there could be a number of factors, but if the DB isn't updating and you're not seeing any PHP errors, then very likely, the issue is with your query.

 

Try echoing the generated UPDATE query string out to your browser, and then copy and paste that into phpMyAdmin or whatever, and see if you can execute the query directly on the DB.

Likely, an syntax error will occur.

 

Please let us know what you find.

Thank you.

  • Upvote 1

Share this post


Link to post
Share on other sites

Hi hartley, thanks for your reply and I really appreciate your help. So far no luck with any of the subsequent scripts after the register script. They either return nothing at all or, when amended, return a 500 Internal Server Error (have asked my host why this is happening). Have today tried the login script to set a cooking but again nothing. Not sure where I am going wrong as have used the scripts downloaded from Larry's site!

 

Am not sure what you mean by 'echoing the generated UPDATE query string out to your browser'. How do I do this?

 

Further, I am using MySql 5.5.32 and PHP 5.3.13. The scripts are from the second edition of Larry's book which covers PHP 5 and MySQL 4.1. Could this have anything to do with why nothing is working?

Share this post


Link to post
Share on other sites

A 500 error means that there is a syntax error in your PHP that has to be fixed.

As for echoing the UPDATE query, I mean if you have a query like the following:

UPDATE users SET name = 'Bob' WHERE id = $user_id;

Then do the following in your PHP script:

echo "UPDATE users SET name = 'Bob' WHERE id = $user_id;";

Doing so will allow you to see the exact query you're executing on the DB, and you can then copy and paste that into phpMyAdmin, and run the query directly on the DB, which will provide more feedback in terms of whether there is an error in the actual SQL, etc.

Share this post


Link to post
Share on other sites

Hi Hartley, starting to make progress. Have established through my web host where the error logs are which are giving information on where the code is wrong. Also using phpMyAdmin to check code. Just worked on the register.php script to get email notifications working. Had to amend the code slightly but after several hours now ok. Have been jumping from script to script when one not working but will next concentrate on the login/logout scripts and try and get working next.

If I get stuck will be back. Many thanks.

Share this post


Link to post
Share on other sites

Hi Hartley, have been working on the login script to set cookies (script 9.1). Again having used the book script the user id and password entered is not being recognised and will not validate the data or create the cookie. Both the email and password entered are correct (ad14@adrianball.london password 'maur33n59'). You can try them at adrianball.london/login.php

 

From what I can see it seems the email and password variables are not being selected from the database or then being used as a cookie and have tried many variations to get the select script to work.

 

When viewed in phpMyAdmin the $query was changed from:

 

$query = "SELECT user_id, firstname FROM students WHERE email='$e' AND password=SHA('$p')";

 

to:

 

$query = "SELECT user_id, firstname FROM students WHERE email=\'$e\' AND password=SHA(\'$p\')";

 

but changing to this returned a syntax error.

 

At present the following error received:

 

The following error(s) occurred:

- The email address and password entered do not match those on file.


Query: SELECT user_id, firstname FROM students WHERE email='' AND password=SHA('')

Please try again.

 

 

 

I also did receive the error: "call to undefined function escape_data".  To correct had to add the following code after the database connection:

 

// Create a function for escaping the data

function escape_data ($data) {
global $dbc; // Need the connection
if (ini_get('magic_quotes_gpc')) {
$data = stripslashes($data);
}
return mysql_real_escape_string(trim($data), $dbc);
} // End of function
 
Any ideas why this won't work?
 
Cheers.

Share this post


Link to post
Share on other sites

Just a tip that might help you. Try without encrypting the password. Maybe even without Escape string. This might help you isolate the error.Add those checks  back in after other code is working.

Share this post


Link to post
Share on other sites

Hi Hartley, I had removed the '\' around the 'email=\'$e\' AND password=SHA(\'$p\' as this would not work.

 

Abigail, unencrypting the password would not work but by removing the escape string the login is working but then fails to set the cookie. I think this may be because it fails to redirect to the logged.php page. After login it displays a blank page which appears to be the login.php page.

 

Have rewritten the set cookie code to use set values that I have tested in a separate php script but this doesn't appear to run. i.e.:

 

$cookie_name = "user";

$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
 
Also do I need to add any variables to define the url the page should redirect to? The code I have is:
 
// Redirect the user to the loggedin.php page.
// Start defining the URL.
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
// Add the page.
$url = '/loggedin.php';
 
header("Location: $url");
exit(); // Quit the script.

Share this post


Link to post
Share on other sites

Hi Larry, good to hear from you. In phpMyAdmin I have run the SELECT query to ensure the records are selected from the database, replacing the variables $e and $p with the actual entries. This runs ok and the line below accepts the user_id and password from the login.php page.

 

SELECT user_id, firstname FROM students WHERE email="$e" AND password=SHA("$p")

 

I'm not sure if the user_id and firstname are then being passed to set the cookie as no cookie is being set and the redirection to loggedin.php is not happening.

 

Have been editing this script for so long now that I forget what I have and have not tried.

 

Don't want to keep posting the login.php script but can do if you wish to see what I have.

 

I am using MySql 5.5.32 and PHP 5.3.13. The scripts I am working with are from the second edition of your book which covers PHP 5 and MySQL 4.1. Could this have anything to do with why I'm having problems?

 

Thanks for taking the time to read.

Share this post


Link to post
Share on other sites

I have used print_r to echo out the select query as follows and only see a blank page so assume this is not selecting the data from the sql database even though the select statement works in phpMySql.

 

$sql = "SELECT user_id, firstname FROM students WHERE email='$e' AND password=SHA('$p')";

$result = mysql_query ($sql); // Run the query.
print_r(mysql_fetch_array($result));

Share this post


Link to post
Share on other sites

You should use the mysqli_query function.

 

Also, please read all the posts from Larry and me above, and carefully try everything we mentioned.

Your answer is in there somewhere.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...