Jump to content
Larry Ullman's Book Forums

Recommended Posts

Sorry for the delay and for the confusion. In Chapter 6, the forum tables are created without mentioning the storage engine, that is true. But in Chapter 7, an ALTER command is used to convert those tables to the MyISAM storage engine (in order to use FULLTEXT searches). So you can't use transactions on those tables because they're aren't the InnoDB type.

 

Got it. Step 3 of adding a FULLTEXT index. Must have completely glossed over that a dozen times. Was convinced I had missed a step. Thanks for clearing it up!

Link to comment
Share on other sites

I have been slowly working my way through the chapter 10 Pursue section and have pretty much completed it, but as I mentioned above on 16 October, the coded solutions are much too big for this forum. They seem to work OK but I make no guarantees that the code could not be better written! I have published them as pdf files at http://www.visitingfife.co.uk/computers/index.html. I have had to add data to the database to make the code work realistically. If anyone wants the edited tables, then I can be mailed at old.graham@gmail.com.

Link to comment
Share on other sites

 

The new 'handle_errors.php'

 

<?php #script 8.2 - display errors
define('LIVE', FALSE);
//create the error handler
function my_error_handler($e_number, $e_message, $e_file, $e_line, $e_vars){

//build the error message
$message = "An error occured in script '$e_file' on line $e_line: $e_message\n";

//append $e_vars to $message
$message .= print_r ($e_vars, 1);

if(!LIVE){//print error if in development
echo '<pre>' . $message . "\n";
debug_print_backtrace();
echo '</pre><br />';
}else{ //don't show error'
echo '<div class="error">A system error occured. We apologise for the inconvenience.<div><br /\>';
}//end if live

}//end my_error_handler function
// You can remove this ?>

 

It seems to work OK for me.

 

As this file will be use as an include file, you can remove the last ?> from your script

Link to comment
Share on other sites

Pheww, seems my solutions for Chapeter 10 - Pursue points 1 to 3 are working, sharing what I have done :

 

Chapter 10

Pursue - P1

* Solution: Modify the string to be passed when clicked on "Edit" and "Delete" from the "view_users.php"

..
// from view_uses.php[/i]
[i]// This code goes inside the [/i]while ($row = mysqli_fetch_array($r, MYSQL_ASSOC)){ conditional
[i]// Just add the new set of variable/values to the URL[/i]

[i]<td align="left"><a href="edit_user.php?id=' . $row['user_id'] . '&fn=' . $row['first_name'] . '&ln=' . $row['last_name'] . '">Edit</a></td>[/i]
[i]<td align="left"><a href="delete_user.php?id=' . $row['user_id'] . '&fn=' . $row['first_name'] . '&ln=' . $row['last_name'] . '">Delete</a></td>[/i]
[i]

 

This info is passed along the url string, so these new elements are available via $_GET (or $_REQUEST), to use this info, just add a conditional at the begining of "edit_user.php" and "delete_user.php" :

 

<?php # Script - edit_user.php
// This page is for editing a user record.
// This page is accessed through view_users.php.
if (isset($_GET['fn']) && isset($_GET['ln'])){
$fn = $_GET['fn'];
$ln = $_GET['ln'];
$page_title = "Edit Info for $fn $ln";
} else {
$page_title = 'Editing User Info';
}
include 'includes/header.html';
....

 

<?php # Script - delete_user.php
// This page is for deleting a user record.
// This page is accessed through view_users.php.
if (isset($_GET['fn']) && isset($_GET['ln'])){
$fn = $_GET['fn'];
$ln = $_GET['ln'];
$page_title = "About to Delete user $fn $ln";
} else {
$page_title = 'Delete a User';
}
...

 

Pursue - P2 and P3

* Solution: Add two password fields to the form, add conditionals to check if the new pass and confirmation pass match. I put the form code in a separate file called edit_form.php, and add it where the form code goes (you can coment out the form code with /* */ to keep the code in your script). Added if else conditionals for checking if the form values where submitted otherwise display the database values"

 

edit_form.php code:

 

<form action="../edit_user.php" method="post">
<fieldset>
 <div><label for="first_name">First Name: </label><input type="text" id="first_name" name="first_name" size="15" maxlength="15" value="<?php if(!empty($_POST['first_name'])) { echo $_POST['first_name']; } else { echo $row[0];} ?>" /></div>
 <div><label for="last_name">Last Name: </label><input type="text" id="last_name" name="last_name" size="15" maxlength="30" value="<?php if(!empty($_POST['last_name'])) { echo $_POST['last_name']; } else { echo $row[1];} ?> " /></div>
 <div><label for="email">Email Address: </label><input type="text" id="email" name="email" size="20" maxlength="60" value="<?php echo $row[2]; ?>" /></div>
 <div><label for="pass">New Password:</label><input type="password" name="pass" id="pass"
		 size="10" maxlength="20" value="<?php if(isset($_POST['pass'])) echo $_POST['pass']; ?>"></div>
 <div><label for="pass1">Confirm Password:</label><input type="password" name="pass1" id="pass1"
		 size="10" maxlength="20" value="<?php if(isset($_POST['pass1'])) echo $_POST['pass1']; ?>"></div>
 <div><input type="submit" name="submit" value="Submit" /></div>
 <input type="hidden" name="id" value="<?php echo $id; ?>" />
</fieldset>
</form>

 

Insert the form:

...
// Create the form:
include 'includes/edit_form.php';
...

 

Add the conditionals for the new password and confirmation password:

 

...
// This code goes inside the if($_SERVER['REQUEST_MEHOD'] == 'POST') {
// And ater the check for an email address conditional
// Check for a new password and match
// against the confirmed password:
if (!empty($_POST['pass'])) {
 if ($_POST['pass'] != $_POST['pass1']) {
	 $errors[] = 'Your new password did not match the confirmed password or you didn\'t enter any.';
 } else {
	 $np = mysqli_real_escape_string($dbc, trim($_POST['pass']));
 }
} else {
 $errors[] = 'You forgot to enter your new password.';
}
....

 

And modify the query to update the password:

 

....
// This goes inside the if (empty($errors)) { in edit_user.php script
// Make the query:
	 $q = "UPDATE users SET first_name='$fn', last_name='$ln', email='$e', pass=SHA1('$np') WHERE user_id=$id LIMIT 1";
	 $r = @mysqli_query ($dbc, $q);
	 if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
...

 

I'd really appreciate any correction,and excuse my writing, english is not my mother language :), I hope some day I could code better than I write english hahaha

 

Thanks!

  • Upvote 1
Link to comment
Share on other sites

Hi Victor,

I read your comment on my solution for the "handle_errors.php" yesterday and that really gave me pause for thought. I tested it in one of my scripts, then I tested it again removing the final ?> as you said. Both work without any obvious error. I suspect that you may well have the right of it but I would be interested to hear from Advanced Members or even Larry on this.

I have had a quick look through your answer(s) for the Pursue Chapter 10 and on my first glance you've come up with similar solutions to myself which reassuring for me. I guess if it works then it is probably OK.

Link to comment
Share on other sites

Hi Graham

 

About removing the closing tag ?> , this what the php manual says:

 

The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include or require, so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later. It is also handy if you use output buffering, and would not like to see added unwanted whitespace at the end of the parts generated by the included files.

 

Thanks for your feedback, chapter 11 comming soon...(now jumping to some javascript)..

Link to comment
Share on other sites

  • 1 month later...

This is just a note to say that I haven't officially created any "Review and Pursue" threads in this forum yet as I didn't know what, exactly, readers would want. So feel free to post your questions as you have them and I'll answer them as they come. In time I may then shuffle things around to create an organized "Review and Pursue" system. Thanks for your interest in the book!

 

Hi Larry, I love the book! Really well put togethor :) I really like the review and pursue parts at the end of each chapter too. Do you have an answers section somewhere so I can check if I am doing things in the correct way, it would be nice to be able to check.

Cheers Matt

 

After searching the forum, I read that there's no answers to the review and pursue. No worries, it would have been nice to see the best way to do each question though. A nice addition to the next issue maybe...

Edited by MattL
Link to comment
Share on other sites

Hi again, and a good new year to all.

I have been working away at chapters 11 and 12 and the Review and Pursue sections. Most of the answers that I came up with for chapter 11 are too long for inclusion in the forum, so I have stuck them as usual in my site at www.visitingfife.co.uk/computers along with the usual caveats.

Chapter 12 answers are (so far) a lot shorter, so here are my stabs at them.

The first bit is a couple of attempts at item 6 of the review, function returning multiple values.

<?php
function demoReturn($rock, $gem, $soil){//create some parameters
if(!empty($rock) && !empty($gem) && !empty($soil)){ // parameters not empty
$genre = array('horror', 'family', 'sci-fi', 'musical', 'fantasy'); //create an array
return $genre; //return the array
}else{//if it went wahoonee shaped
echo 'Give the function some values!';
}
}
$info = demoReturn('hardstuff', 'shinything', 'mud'); //call the function and enter some parameters
foreach ($info as $v){ //foreach loop to display the array values
echo ' - '. $v . '<br />'; //show array returned by the function
}

function demoReturn2($some, $more){//some parameters
if (!empty($some) && !empty($more)){//were values entered into the parameters?
$lots = array_merge ($some, $more); //set variable for the 2 arrays added together
$many = implode( " ", $lots);//change merged array to a string
return $many;//return the string
}else{
echo 'Give the function some values!';
}
}
$herd = array('Ant', 'Bear', 'Cat', 'Dog', 'Elk');//an array
$herd2 = array('Zebra', 'Yak', 'Warthog');//another array
$amount = demoReturn2($herd, $herd2);//call the function
echo $amount ; //display the function results
?>

 

Next up is the 3rd item of Ch 12 pursue. The best answer I came up with is not in fact mine. Best to look at http://www.larryullm...ursue-number-3/ for a discussion of this topic.

 

For the 4th item, modify redirect_user(), I thought of several ways of doing this finally deciding that this was at least as good as any.

The line $url .= '/ch12test/'; is just the directory where I put the file(s) to be redirected to. I also stuck the index.php in the ch12test directory. The 2 directories (ch12 and ch12test) are in the same parent directory.

You would have to change the line (line 22) that calls the function in the login.php script to suit your own purposes. Since this was an experiment I stuck in redirect_user('ch12redirect.php');//test version.

function redirect_user ($page = 'index.php'){
$url = 'http://' . $_SERVER['HTTP_HOST'];//root directory
$url .= '/ch12test/';//directory containing file
$url .= $page;//file
header ("Location: $url"); //site1/ch12test/$page: variable containing the file redirected to
exit; //kill the script
//redirect the user:
header("Location: $url");
exit(); //quit the script
}//end of redirect_user() function

 

The 5th item, using a cookie to store a user preference, was the one I have so far found most interesting. The idea of allowing a user to interact with a web page to choose formatting is compelling. I have kept this VERY simple just to show the principle. The code and css is below. The css was in 3 external files (blue.css etc).

blue.css file
p{ color: blue; }

red.css file
p{ color: red; }

green.css file
p{ color: #00782B; }

<?php
if ($_SERVER['REQUEST_METHOD']=='GET'){
$colour = 'blue';
echo '<link rel="stylesheet" href="$colour.css" type="text/css" media="screen" />';
}else{//not sure this is the best way...
//if ($_SERVER['REQUEST_METHOD']=='POST'){
$colour = $_POST['colour'];
setcookie('colour', $colour);
}
?>
<link rel="stylesheet" href="<?php echo "$colour.css" ?>" type="text/css" media="screen" />
<!--form to make choices-->
<form action="choose_colour.php" method="post">
<p>Colour?: <input type="radio" name="colour" value="blue" checked="checked" />Blue
<input type="radio" name="colour" value="red" />Red
<input type="radio" name="colour" value="green" />Green</p>
<p>Submit: <input type="submit" name="submit" value="submit" /></p>
</form>

 

And so far, that's all. Hope it wasn't too long. I have run all of it and it seems to run OK.

Link to comment
Share on other sites

  • 4 weeks later...

Just want to say what an excellent book this is, i.e. "PHP for the Web" [4th edition].  

 

I very much like the writing, the pace of instruction, the layout and everything else.

 

I had minor problems in spacing because of the narrow layout columns that force code onto the next line - couldn't see if two characters were right next to each other or if there was actually a space between them.  The little grey arrows on the left side of the code could be either a space or a hard return, no?  It actually hasn't caused me any real problems, though, since I can deduce from context whether I need a space or a hard return.

 

Curious thing, your images just to right of, e.g. the "#3" etc.on this page :

 

<img src="http://www.larryullman.com/forums/public/style_images/larry_ullman/icon_share.png" class="small" title="Review And Pursue: post #5">

 

are not showing up in Chrome (latest version as of Feb 11, 2013).

 

They show up in Firefox ok.

 

Also, what would be a good book - of yours - to follow this one?  That is, to take me to the next level of PHP programming.  I shall check the book list ...

 

Many thanks,

Bruce Conway

Link to comment
Share on other sites

Bruce, I had the same issue with the narrow columns and the spacing.

Probably the best solution is to download all the code in the book from the following page on this site (because it's much easier to view the code in a text editor):

http://www.larryullman.com/books/php-and-mysql-for-dynamic-web-sites-visual-quickpro-guide-4th-edition/#downloads

 

Also, which book to go to after this book somewhat depends on what you what to focus on, but if you want to focus on JS, then Larry's JS book is good. If you'd rather focus on PHP, then either Larry's e-commerce book or his advanced PHP book would be a good choice. If you'd prefer a shorter (but no less useful) read, then Larry's Ajax book might be good.

 

I personally would recommend a combination of the JS book and the e-commerce book.

All the same, good luck.

Link to comment
Share on other sites

Hello Bruce,

 

Thanks for the nice words on my work. It is appreciated. (Thanks, too, for pointing out the missing image. It's fixed now.) 

 

As for your question, to go to the next level of PHP programming, you should read the "PHP & MySQL for Dynamic Web Sites" book. There is some overlap with the book you just read (particularly in the early chapters), but it uses new examples for those and then takes everything  much, much farther, including real-worl applications. In my mind, going from the "PHP for the Web" book to either the e-commerce book or the PHP Advanced would be a pretty sizable jump in content. 

Link to comment
Share on other sites

  • 1 month later...

Hello! 

I'm attempting to rewrite handle_form.php to validate the age element

 

 

 

 

   //validate age:
    if (isset($_REQUEST['age'])) {
        
        $age = $_REQUEST['age'];
    if ($age == '0-29') {
        echo '<p><b>You are 0-29!</b></p>';
    }elseif ($age == '30-60') {
        echo '<p><b>You are 30-60!</b></p>';
    }else($age == '60+'){
        echo  '<p><b>You are 60+!</b></p>';
    }
 

That's what I have so far.  Thanks very much, it's a great book so far!

 

 

Link to comment
Share on other sites

There's nothing wrong with your code but you might want to consider incorporating an associative array which would reduce your if elseif statement down to one line of code. Also if you are using a select field in your html form it would allow you to code all your options with just one line. It's a good way to test your understanding of arrays. Let us know if you have any questions :)

Link to comment
Share on other sites

if (isset($_REQUEST['age'])) {
  
  echo '<p><b>You are ' . $_REQUEST['age'] . '!</b></p>';
  
}

 works nicely. I was thinking that he could do a bit more

$ages=array('0-29' => 'young', '30-60'=> 'middle aged', '60+'=>'old');
    if (isset($_REQUEST['age'])) {
        $age = $_REQUEST['age'];
        echo '<p><b>You are ' . $age .'!</b></p>';
        echo '<p><b>You are ' . $ages[$age] .'!</b></p>';
	}

and in the html

<form action="#" method="post">
<p>Age: 
<select name="age">
<?php
foreach ($ages as $key=> $value) {
echo "
<option>{$key}</option>";}

?>
</select>

 

Link to comment
Share on other sites

Thanks guys but before moving forward I'd like to know why I am getting a parse error on the 60+ else conditional line:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>Form Feedback</title>
	<meta name="generator" content="TextMate http://macromates.com/">
	<meta name="author" content="Michael Wiss">
	<!-- Date: 2013-03-14 -->
	<style type="text/css" title="text/css" media="all">
	.error {
		font-weight: bold;
		color:#C00;
	}
	</style>
</head>
<body>
	<?php # Script 2.4 - handle_form.php #3
	
	//validate the name:
	if (!empty($_REQUEST['name'])) {
		$name = $_REQUEST['name'];
	} else {
		$name = NULL;
		echo '<p class="error">You forgot to enter your name!</p>';
	}
	//Validate the email:
	if (!empty($_REQUEST['email'])) {
	$email = $_REQUEST['email'];
	} else {
	 $email = NULL;
	echo '<p class="error">You forgot to enter your email address!</p>';
}
	//validate the comments:
	if (!empty($_REQUEST['comments'])) {
		$comments = $_REQUEST['comments'];
	} else {
		$comments = NULL;
		echo '<p class="error"> You forgot to enter your comments!</p>';
	}
	//validate the gender:
	if (isset($_REQUEST['gender'])) {
		
		$gender = $_REQUEST['gender'];
		
		if ($gender == 'M') {
			echo '<p><b>Good day, Sir!</b></p>';
		} elseif ($gender == 'F') {
			echo '<p><b>Good day, Madam!</b></p>';
		} else {// Unacceptable value.
			$gender = NULL;
			echo '<p class="error>Gender should be either "M" or "F"!</P>';
		}
	} else { // $_REQUEST['gender'] is not set.
		$gender = NULL;
		echo '<p class="error">You forgot to select your gender!</p>';
		}
		
		//validate age:
	if (isset($_REQUEST['age'])) {
		
		$age = $_REQUEST['age'];
	if ($age == '0-29') {
		echo '<p><b>You are 0-29!</b></p>';
	}elseif ($age == '30-60') {
		echo '<p><b>You are 30-60!</b></p>';
	}else($age == '60+'){
		echo  '<p><b>You are 60+!</b></p>';
	}
		//IF everything is OK, print the message:
	if($name && $email && $gender && $comments && $age) {
		
		echo "<p>Thank you, <b>$name</b>, for the following comments:<br />
		<tt>$comments</tt></p>
		<p>We will reply to you at <i>$email</i>.</p>\n";
		
	} else { //Missing form value.
		echo '<p class="error"> Please go back and fill out the form again.</p>';
		}
	?>
	
</body>
</html>

 

 

 


Link to comment
Share on other sites

That is why you use arrays - to get rid of all those difficult to maintain (not to mention ugly) if elseif elseif statements. May I suggest you try using some arrays for the age conditional and for the gender conditional. You will make a leap as a programmer when you recognise opportunities to streamline your code.

Link to comment
Share on other sites

  • 1 month later...

I have a question about chapter 9. I am probably just missing something easy. In the review and pursue section of chapter nine the last pursue question. This question refers to a banking database. Where can this database be found or was it created in a previous chapter?

Link to comment
Share on other sites

 Share

×
×
  • Create New...