Jump to content
Larry Ullman's Book Forums

old.graham

Members
  • Posts

    27
  • Joined

  • Last visited

  • Days Won

    1

Everything posted by old.graham

  1. Thank you to Deaddog for his view_users.php (script 10.5) code which solved a problem for me. I wanted to switch form ASC to DESC for the lists, and got about halfway there, but this solved the problem for me. I have altered it slightly to suit my own requirements but gave honourable mention in the comments.
  2. Hi Larry, Thank you for your very prompt reply. I take it then that finfo_file() is going to depend on browser variety? Firefox may possibly give different results from IE or Chrome? I guess then that finfo_file() would be the one to use where the file's attributes/MIME type is critical. Gratitude for unravelling that. old.graham
  3. Hi and thanks in advance. I run apache 2.2.22 , php 5.3.10-10 in Ubuntu 12.04. I have been working through the chapter13 Review and Pursue topics . The Pursue 4/5th topics suggest modifying the upload_rtf.php code. I have added code to display the name, type and size of a file that has been offered for uploading. I get some unexpected and inconsistent results for MIME types for an RTF file type and also some other file types. The relevant code is: //indicate it's OK: also print file MIME type echo '<p><em>The ' . finfo_file($fileinfo, $_FILES['upload']['tmp_name']) . ' file would be acceptable.</em></p>'; //print_r($_FILES['upload']) ; //just testing the array echo '<p><em>The file <b>' . $_FILES['upload']['name'] . '</b> is a MIME type ' . $_FILES['upload']['type'] . '. The file size is ' . $_FILES['upload']['size'] . ' bytes.</em></p>'; When the code is executed in the browser (Firefox 17.0.1): An rtf file is given as text/rtf by one line then application/rtf by the next line. A php file is given as text/x-php on the first line then application/x-php by the second line. However, a jpg or gif file is given as image/jpg or image/gif on both lines. I have looked around the 'net for explanations, but haven't found anything that led to an understanding of how this occurs. Can anybody suggest why this should be?
  4. 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.
  5. Finally, I get it. Thanks for the second post, Larry. That was the one that clinched it for me. I had the same problem as HartleySan and had to read the posts several times. Still puzzled, I walked away from it and had a Eureka moment about an hour later. My code above is unnecessary. You don't have to force the error to be string or array, but I wouldn't have got it without all the input from the Advanced Members. All the best for the New Year to you all.
  6. After my less than useful last post, I thought about it overnight. I came up with this. Is this the sort of thing that would satisfy the question? <?php //define variables //$wrong1 = 'This the wrong1'; $wrong1 = ''; //$wrong2 = 'This is the wrong2'; $wrong2 = ''; if(empty($wrong1)){//if var is empty assign message to var $err1 = 'Wrong1 empty.'; }else{//no worries echo 'Wrong1 is right<br />'; } if(empty($wrong2)){//if var is empty assign message to var $err2 = 'Wrong2 is empty'; }else{//no worries echo 'Wrong2 is right<br />'; } if(empty($wrong1) && empty($wrong2)){//if both empty $error = array($err1, $err2);//create an array of error messages }elseif(empty($wrong1)){//only one wrong $error = $err1;//assign a message to $error }elseif(empty($wrong2)){ $error = $err2; }else{ $error = 'No problems.';//if all variables have values } if(is_array($error)){//is it an array? foreach($error as $msg){ echo " - $msg<br />";//display the error messages } }else{ echo " $error";//only one value missing } ?>
  7. 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.
  8. 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.
  9. I finally got around to chapter 10 Review and Pursue section after getting VERY sidetracked with chapter 9 Review and Pursue, banking database. I haven't added any error checking just to keep it simple. In order to get the edit.php and delete_user.php to display the user name in the browser title bar (and also the header because it looks good) I found that I had to change some lines in the view_user.php script. Lines 76-86 (page 324) I replaced with: while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ extract($row);/*this allows variables with the same name as the $row['something'] to be created. e.g $row['something'] becomes $something I came across this and thought it a neat trick */ $bg = ($bg == '#CCC' ? '#FFF' : '#CCC'); echo'<tr bgcolor="' . $bg . '"> <td align="left"><a href="edit_user.php?id=' . $user_id . '&fn=' . $first_name . '&ln=' . $last_name . '">Edit</a></td> <td align="left"><a href="delete_user.php?id=' . $user_id . '&fn=' . $first_name . '&ln=' . $last_name . '">Delete</a></td> <td align="left">' . $user_id . '</td> <td align="left">' . $last_name . '</td> <td align="left">' . $first_name . '</td> <td align="left">' . $dr . '</td> </tr> '; }//end of while loop In the delete_user.php script, I added: if ($_SERVER['REQUEST_METHOD']=='GET'){ $page_title= 'Delete User: '. $_GET['fn'] . ' ' . $_GET['ln']; }else{ $page_title="Delete User: " . $_POST['first_name'] . ' ' . $_POST['last_name']; } //and then the header and title as before include ('includes/header.html'); echo '<h1>Delete a User</h1>'; //check for valid user ID, through GET or POST if ((isset($_GET['id'])) && (is_numeric($_GET['id']))){//this page accessed from view_user.php $id = $_GET['id']; $fn = $_GET['fn'];//needs this to pass to form $ln = $_GET['ln'];//needs this to pass to form }elseif((isset($_POST['id'])) && (is_numeric($_POST['id']))){//submitted from this page and form $id = $_POST['id']; $fn = $_POST['first_name'];//from form from $_POST $ln = $_POST['last_name'];//from form from $_POST }else{//no valid ID. end script echo '<p class="error">This page has been accessed in error.</p>'; include ('includes/footer.html'); exit(); } I also made some additions to the <form> that starts at line 59 on page 305: //create the form echo '<form action="delete_user.php" method="post"> <input type="radio" name="sure" value="Yes" />Yes <input type="radio" name="sure" value="No" checked="checked" />No <input type="submit" name="submit" value="Submit" /> <input type="hidden" name="id" value =" ' . $id . '" /> <input type="hidden" name="first_name" value =" ' . $fn . '" /> <input type="hidden" name="last_name" value =" ' . $ln . '" /> </form>'; These last 2 inputs pass hidden values to $page_title. In the edit_user.php script, I made the following changes: //change page title to suit user to be edited as per Review and Pursue chapter 10: not secure: just to show principal if ($_SERVER['REQUEST_METHOD']=='GET'){ $page_title= 'Edit User: '. $_GET['fn'] . ' ' . $_GET['ln']; }else{ $page_title='Edit User: ' . $_POST['first_name'] . ' ' . $_POST['last_name']; } //and then the header and title include ('includes/header.html'); echo '<h1> Edit User Details</h1>'; I also added the following lines to the UPDATE query that starts on line 56. This displays a message if nothing has been altered and prevents an error message. }elseif(@mysqli_affected_rows($dbc)==0){//no row changed: no new details //display message echo '<p>No new details have been inserted.</p>'; Hope this lot helps someone. For the 2nd Pursue question, I am creating a version of edit_users.php that allows the changing of a user's password which is a cross between the change_password script and the edit_user script. My take on this is more complex than the suggestion on one of the sidebars in chapter 10, page 315. I have hesitated to publish it in the forum as it currently runs to 145 lines of code. Once I add the error/security checking it will run to rather more. I therefore intend to display it on a page on my site at www.visitingfife.co.uk as soon as I am happy with it.
  10. Hi Antonio, Thanks for looking in again. Earlier in the script each of the user inputs are treated thus: //check for first name if(empty($_POST['first_name'])){ $errors[] = 'You forgot to enter your first name'; }else{ $fn = mysqli_real_escape_string($dbc, trim($_POST['first_name'])); //validate user input } Is this enough or should there be further checks on input? I have seen forums where prepared statements are recommended, but that looks a bit advanced for this forum _ and for me _ as yet.
  11. Thanks for the suggestion. I have altered all the relevant code in my IDE to help me remember that. I now make my offering for Q4 page 298 using mysqli_affected _rows(). I have just posted what I believe to be the relevant bit. Hope I got this OK. //make the query $query = "INSERT INTO users (first_name, last_name, email, pass, registration_date) VALUES ('$fn', '$ln', '$email', SHA1('$password'), NOW() )"; $request = @mysqli_query ($dbc, $query);//run the query if (mysqli_affected_rows($dbc) == 1){//if it ran OK should be 1 row only changed //display message echo '<h1>Thank you!</h1> <p>You are now registered. In Chapter 12 you will be able to (gasp) log in!</p> <p><br /></p>'; I am going to mess about with queries for the next couple of weeks as mentioned in the final part of the Review and Pursue ch9 because I can use the practice!
  12. Hi Antonio, Does this fit the bill? //check for email if(empty($_POST['email'])){ $errors[] = 'You did not enter your email.'; }else{ $email = mysqli_escape_string($dbc, trim($_POST['email'])); //this is escaped bit //make a query to check if email is already in use $q = "SELECT user_id FROM users WHERE email = '$email'"; $r = @mysqli_query($dbc, $q); $n_rows = mysqli_num_rows($r); if ($n_rows > 0){ $errors[] = 'This email address is already in use.'; }else{ $email = mysqli_escape_string($dbc, trim($_POST['email'])); }//end if email already in use }//end if empty email Thanks for your taking the time to check this for me. I tend to learn much from what I get wrong and it really helps when someone points out my mistakes.
  13. Hi Antonio, Thanks for the heads up on that, but it has me really puzzled _ unless you mean the error suppressor operator? If that is what you mean then you are quite correct and I should have it in. That would then be $r = @mysqli_query($dbc, $q); If that's not it, can you be more explicit because I can't think what else it could be? Thanking you in advance and mea culpa for the fault. I have just noticed another error in the code. I have inserted the code fragment in the wrong place. It should go in line 33. As it was, it only works if all the other inputs have been filled. I cover my eyes in shame.
  14. Hi Larry, Thanks for your comment. But your book really makes it so easy I can take very little credit. Any road up, here is my solution to the 4th question on the chapter 9 Pursue and Review using mysqli_num_rows() function to test for previous use of the email address. //make a query to check if email is already in use $q = "SELECT user_id FROM users WHERE email = '$email'"; $r = mysqli_query($dbc, $q); $n_rows = mysqli_num_rows($r); if ($n_rows > 0){ $errors[] = 'This email address is already in use.'; }else{ $email = mysqli_escape_string($dbc, trim($_POST['email'])); }//end if email already in use This is inserted below line 45 and above line 46 register.php script on page 287. I have tested it and it works fine for me. I use $email rather than $e as a variable name to make it clearer for myself.
  15. Another post: solution to Chapter 9 Review and Pursue, Pursue topic 3: In view_users.php: To use the mysqli_num_rows($result) as a boolean value to test TRUE, I simply removed line 19 if ($num > 0 ){//if any records returned and substituted if (mysqli_num_rows($result)){ Very simple _ and it seems to work all right.
  16. Just posting my solution to Chapter 9 Review and Pursue, Pursue topic 2 _ Custom error handler : It seemed the easiest way to do this was to strip the handle_errors.php script of everything that wasn't inside the php tags,and remove line 36 and save the revised script in the same folder as the other php scripts as handle_error.php. I then added to view_users.php on line 6 include ('handle_errors.php'); which is under line 5 includes ('header.php'); then added on line 7 set_error_handler ('my_error_handler'); 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 ?> It seems to work OK for me.
  17. Hi Rafaec, I haven't got as far as you in the book so I can't answer your question. I've just been posting here what I think might be the answers to the Review and Pursue. Like you I am not always sure what Larry has in mind when he asks the questions. Could be the questions are just to make sure you have thought the thing through and are familiar with the code ideas and concepts and there are no hard answers? Larry will no doubt answer this better than anyone. Anyhow here is my take on chapter 3's last 3 questions which I have concatenated into one script. <?php function create_radio($value, $button_name){ echo '<input type="radio" name="' . $button_name . '" value="' . $value . '"'; if (isset ($_POST[$button_name]) && ($_POST[$button_name] == $value)){ echo ' checked = "checked"'; } echo " /> $value \n"; }//end of function ?> <form action="radio_review.php" method="post"> <p>Average Speed: <input type="text" name="speed" value="<?php if (isset($_POST['speed'])) echo $_POST['speed']; ?>"/></p> <p>Distance in Miles: <input type="text" name="distance" value="<?php if (isset($_POST['distance'])) echo $_POST['distance']; ?>"/></p> <p>Fuel Efficiency: <select name="efficiency"> <option value="10" <?php if (isset($_POST['efficiency']) && ($_POST['efficiency'] == 10)) echo 'selected = "selected"'; ?>>Terrible</option> <option value="20" <?php if (isset($_POST['efficiency']) && ($_POST['efficiency'] == 20)) echo 'selected = "selected"'; ?>>Decent</option> <option value="30" <?php if (isset($_POST['efficiency']) && ($_POST['efficiency'] == 30)) echo 'selected = "selected"'; ?>>Good</option> <option value="50" <?php if (isset($_POST['efficiency']) && ($_POST['efficiency'] == 50)) echo 'selected = "selected"'; ?>>Excellent</option> </select></p> <?php $fuel_price = array('3.00', '3.50', '4.00'); //create array $number = count($fuel_price); //count items in array echo "<p>Fuel Price :"; $x = 0; while ($x < $number ) { //while $x is less than the number of items in array create_radio($fuel_price[$x], 'fuel');//call function $x++; //add 1 to $x }//end while loop echo "</p>"; $cost = ($_POST['distance']/$_POST['efficiency'])*$_POST['fuel']; $time = $_POST['distance']/$_POST['speed']; echo '<p>Cost of a journey of ' . $_POST['distance'] . ' miles at $' . $_POST['fuel'] . ' per gallon is $' . number_format($cost, 2) . '.</p>'; if ($time > 24){//if the journey time is more than 24 hours $days = $time/24; $days = round($days);//round the answer down to nearest whole number $hours = $time%24; //modulus echo '<p>The journey will take you: ' . $days . ' days and ' . number_format($hours,2) . ' hours</p>'; }else{ echo '<p>The journey will take you ' . number_format($time,2) . ' hours.</p>'; } ?> <input type="submit" name="submit" value="Submit" />
  18. The whole new form would be too much for a forum, so I have limited the new form to just the textarea and checkbox not described in the book. <?php # A solution to Review and Pursue chapter 3 page 110: Create a new sticky form. # I have supplied a header.html and footer.html to accompany this form. # The css I submitted above works with this form. # The form looked a bit bland, so I have included additional styling in the header.html file # rather than rewrite the whole of the css file. # I am indebted to http://www.phpfreaks.com/forums/index.php?topic=139571.0 boo_lolly for checkbox code design. # Author old.graham June 2012 using Aptana on Ubuntu Linux: PHP 5.3.3-1: Apache 2.2.16 $page_title = "Review and Pursue _ Sticky Form"; include ('includes/header.html'); ?> <h1>Review Solutions</h1> <h2>Sticky form</h2> <form action="review_stickyform.php" method="post"> <!--create a form--> <!--checkbox with php arrays--> <p><label for="tickbox">Checkbox: <?php $tickvalues = array('Ant', 'Bat', 'Cat', 'Dog');//checkbox titles foreach ($tickvalues as $key => $value){ echo "<input type=\"checkbox\" name=\"tickbox[]\" value=\"{$value}\""; foreach ($_POST['tickbox'] as $index => $checked){ if ($value == $checked){ echo ' checked = "checked"'; }//test for checked } echo " />{$value}\n"; //tick checked values } ?> </label></p> <!--textarea with php to make it sticky--> <p><label>Textarea:<textarea name="textareas" rows="3" cols="40" ><?php if (isset($_POST['textareas'])) {echo $_POST['textareas'];}?></textarea></label></p> <!--and finally, the submit button--> <p><input type="submit" name="submit" value="Submit" /></p> </form> <p> </p> <?php if ($_SERVER['REQUEST_METHOD'] == 'POST'){//has the form been submitted using POST? //some validation: has anything been entered? $animals = implode(', ', $_POST['tickbox']); //turn array from checkbox into a comma separated string if (!empty($_POST['textareas']) && isset($animals)){ //display results echo 'In the Checkboxes, you ticked: <i>' . $animals . '</i><br />' ."\n" . 'In the Textarea, you wrote: <i>' . $_POST['textareas'] . '</i>'; }else{//displayed if values missing echo 'Please complete the form.'; } }//end if submitted with POST ?> <?php include ('includes/footer.html'); ?>
  19. ...and here is the footer ... <!--end of page specific content--> <!--rewritten for Review and Pursue chapter3: footer.html--> </div> <div id="footer"> <p>Copyright © <a href="#">Awfy Simple</a> 2012 | Designed by <a href="http://www.opendesigns.org/">Old Graham </a> | Valid <a href="http://jigsaw.w3.org/css-validator/">CSS</a> & <a href="http://validator.w3.org/">XHTML </a></p> </div> </body> </html>
  20. Thanks for replying so quickly. Sorry. I can see that adding code piecemeal might be a bit confusing. It takes me ages to format the code so that it is easier to read since I don't seem to be able to paste it with the formatting that gedit or Aptana provide. The css goes with the ability to change the look of the entire site. The previous css file would be named style.css to work with the header. The footer follows shortly. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link rel="stylesheet" href="includes/style.css" type="text/css" media="screen" /> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title> <?php echo $page_title; ?> </title> <style type="text/css" title="text/css" media="all" ><!--additional styling for forms--> label,legend{ font-weight: bold; color: #300acc; } form{ background-color: #cccccc; } </style> </head> <body> <div id="header"> <h1><?php echo $page_title ?></h1> <h2>better the deil ye ken...</h2> </div> <div id="navigation"> <ul> <li><a href="index.php">Home Page</a></li> <li><a href="calculator.php">Calculator </a></li> <li><a href="review_stickyform.php" >Sticky Form </a></li> <li><a href= "http://www.larryullman.com">Larry Ullman </a></li> <li><a href="http://www.ubuntu.com">Ubuntu </a></li> </ul> </div> <div id= "content"><!--start of page specific content--> <!--written for Review and Pursue chapter 3: header.html-->
  21. Hi Larry, First offering for chapter 3... I have followed the formatting used by gedit in Linux (Ubuntu) so I hope that this is more readable. Thanks for your kind comments on my trade. /*Review and Pursue chapter 3 page 110 PHP and MySQL edition4 *This is a new css template for use on pages in chapter 3 *author old.graham June 2012 */ body{ margin:auto; border: 0px; padding: 0px; background: #EBECF6; width: 950px; } a{ text-decoration: none; color: #4A2885; } a:hover{ color: blue; } #header{ border-style:solid; border-width: 2px; border-color: #BFB2D3; width: 950px; height: 80px; background-color: #F5F8EC; } #header h1{ text-align: center; margin-bottom: -20px; } #header h2{ text-align: right; margin-top: 10px; color: gray; } #navigation{ width: 950px; text-align: left; margin-left: -40px; } #navigation li{ width: 135px; height: 19px; list-style: none; border-width: 2px 1px 1px 2px; display: inline-block; border-style: solid; border-color: #BFB2D3; } #navigation a{ display : block; colo r: navy; font-family: Arial, Helvetica, sans-serif; font-weight: bold; text-decoration: none; background-color: #F5F8EC; text-align: center; } #navigation a:visited{ color: gray; text-decoration: none; background-color: white; } #navigation a:hover{ color: blue; background-color: silver; } #content{ margin: auto; width: 950px; height: 100%; font-family: Arial, Helvetica, sans-serif; color: #555555; } #content h1{ color: navy; } #footer{ width: 950px; margin: 0 auto; text-align: center; }
  22. I will be happy with any advice you feel able to give and try to follow it. I hoped that the code and your comments and advice on this code would be of help to me and other readers/student PHP code writers who have difficulty with the Pursue pages or are curious about other ways of doing things. I shall have a look at using forum formatting tags on the code and in an attempt to make it more readable. The formatting (line spacing and tab/margins) in the IDE I use (Aptana on Ubuntu 10) seems to get lost when I cut and paste. In the past when I have been stuck with a problem, I have found maybe a few lines of code in forums that helped me immensely. I feel that now I can pay back the debt to the wider community by offering some ideas and examples that seem to answer the questions posed in the Pursue section. I am a dilettante in this field (a welder to trade) and study code and computing for intellectual stimulation, occasionally designing and implementing websites for friends for doughnuts and coffee. If this forum is not the appropriate place for this, or if I am being presumptuous, please tell me and I will cease from posting here. Thank you for your time.
  23. Oops. I should have put in some /n to make the source code readable. Thought of it just after I posted. Apologies.
  24. Thanks for the comments and for taking the time to reply. The double quotes was just silly of me. I wish I had thought of using the number _format that way. Just good style from a pro. I shall take on board the variable names comments. I have now got some more. The code for the ch 2 review and pursue is getting kind of big for posting here but I shall await your feedback on this. I suppose if it is just copied and pasted into and IDE it will be more readable. I hope this may be of some use to someone. I await your feedback with trepidation. PHP version? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>PHP Version</title> </head> <body> <?php #script chapter2 review and pursue page 73 phpinfo();//gives all details of php installed echo '<br /> PHP version is ' . PHP_VERSION; //just the version ?> </body> </html> All the rest of the form and handler: pursue_form.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>HTML Feedback Form</title> <style type="text/css" title="text/css" media="all" > label,legend{ font-weight: bold; color: #300acc; } form{ background-color: #cccccc; } </style> </head> <body> <!--script 2.1 form.html--> <form action="handle_pursue_form.php" method="post"> <fieldset><legend>Please enter your information in the form below:</legend> <p><label>Please complete all entries.</label></p> <p><label>First Name: <input type="text" name="fname" size="20" maxlength="40" /></label></p> <p><label>Last Name: <input type="text" name="lname" size="20" maxlength="40" /></label></p> <p><label>Email address: <input type="text" name="email" size="40" maxlength="60" /></label></p> <p><label for="gender">Gender: </label> <input type="radio" name="gender" value="male" /> Male <input type="radio" name="gender" value="female" /> Female</p> <p><label>Age: <select name="age"> <option value="0-24">Under 25</option> <option value="25-64">Between 30 and 60</option> <option value="65+">Over 60</option> </select></label></p> <p><label>How many times have you used the garage? <select name="use"> <option value="1">First time</option> <option value="<6">2 to 5 times</option> <option value=">5">More than 5 times</option> </select></label></p> <p><label>How did we do? (choose one only): </label></p> <p><input type="checkbox" name="quality[]" value="poor" />Poor</p> <p><input type="checkbox" name="quality[]" value="average" />Average</p> <p><input type="checkbox" name="quality[]" value="good" />Good</p> <p><input type="checkbox" name="quality[]" value="great" />Great</p> <p><input type="checkbox" name="quality[]" value="excellent" />Excellent</p> <p><label>What work did we do on your last visit? Choose all that apply: </label></p> <p><input type="checkbox" name="service[]" value="mot" />MOT</p> <p><input type="checkbox" name="service[]" value="mot repairs" />MOT Repairs</p> <p><input type="checkbox" name="service[]" value="air con recharge" />Recharge Air Conditioning</p> <p><input type="checkbox" name="service[]" value="tyres" />Tyres</p> <p><input type="checkbox" name="service[]" value="car servicing" />Car Servicing</p> <p><input type="checkbox" name="service[]" value="other work" />Other Work</p> <p><label>Any comments? What can we improve on? <textarea name="comments" rows="3" cols="40"></textarea></label></p> </fieldset> <p align="center"><input type="submit" value="Submit Information" /></p> </form> </body> </html> handle_pursue_form.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>Form Feedback</title> <style type="text/css" title="text/css" media="all" > label,legend{ font-weight: bold; color: #300acc; } form{ background-color: #cccccc; } .error{ color: #C00; font-weight: bold; } </style> </head> <body> <?php #script page 73 pursue. I have concatenated most of the page 73 questions in this one script //validate the gender: //rewrite gender conditional //is this what was asked for or have I misunderstood the question? //was anything selected and was it male or female if(isset($_POST['gender']) && (($_POST['gender']=='male')) ){//value checked AND male //value checked $gender = $_POST['gender'];//male $title = 'Mr.'; }elseif(isset($_POST['gender']) && $_POST['gender']=='female'){//value checked AND female $gender = $_POST['gender']; //female $title = 'Ms.'; }else{//radio button not checked $gender = NULL; $title_error = '<p class="error">Gender should be either male or female.</p>';//error message } //validate the first name if (!empty($_POST['fname'])){//first name entered $fname = $_POST['fname']; }else{//nothing entered in the box $fname = NULL; $fname_error = '<p class="error">You did not enter your first name.</p>'; //error message } //validate the last name if (!empty($_POST['lname'])){//last name entered OK $lname = $_POST['lname']; }else{//no last name entered $lname = NULL; $lname_error = '<p class="error">You did not enter your last name.</p>';//error message } //validate number of times garage used //couldn't resist trivial use of switch function if ((isset($_POST['use']))){ $use = $_POST['use']; switch ($use) { case '1': $greeting = 'Nice to see a new customer '; break; case '<6': $greeting = 'Great to see you back again'; break; case '>5': $greeting = 'Welcome back '; break; default: $greeting_error = '<p class="error">You have not told us how many times you have used the garage.</p>';//no number of visits selected error message break; } }else{//error message $greeting_error = '<p class="error">Please indicate how many times you used the garage</p>';//no number of visits selected error message } //validate email if(!empty($_POST['email'])){ //if the box is not empty $email = $_POST['email']; }else{//no mail address entered $email = NULL; $email_error = '<p class="error">You did not enter your email.</p>'; } //validate the comments if(!empty($_REQUEST['comments'])){//if the box is not empty $comments = $_REQUEST['comments']; }else{//no comments entered $comments = NULL; $comments_error = '<p class="error">You made no comments.</p>';//no comment error message } //validate age if (isset($_POST['age'])){//selection made $age = $_POST['age']; if($age=='0-24'){ $age_message = '<p>Your age is given as under 25 years old. You may qualify for a student discount.</p>'; }elseif ($age =='25-64'){ $age_message = '<p>Your age is given as between 25 and 60. If you are in part time employment or unemployed, you may qualify for a reduced rate.</p>'; }elseif ($age == '65+'){ $age_message = '<p>Your age is given as above 65 years old, so you may qualify for our pensioners discount.</p>'; }else{ $age = NULL; $age_error = '<p class="error">Please choose a value for your age.</p>';//no age chosen error message } }else{//nothing selected $age = NULL; $age_error = '<p class="error">You did not select an age.</p>';//error message } //how did we do? Array. If more than one box ticked give error message if (isset($_POST['quality'])){//at least one box ticked $quality = $_POST['quality']; $num = count($quality); //trivial use of count: better as radio button if ($num == 1){//if just one box ticked foreach ($quality as $k => $v){ $quality_ok = '<p>You have found our service to be ' . $v . '.</p>';//this only works because only one value can be printed } }else{//too many boxes ticked $quality = NULL; $quality_error = '<p class="error">You ticked ' . $num . ' boxes. Please make only a single choice for quality of service.</p>';//error message using count function } }else{//no box ticked $quality = NULL; $quality_error = '<p class="error">You made no choice of quality of service. Please tick one box.</p>';//error message } //what services did we provide? Array if (isset($_POST['service'])){//if box/boxes ticked $service = ($_POST['service']); sort ($service);//sort in alphabetical order //shuffle($service);//randomly sort the list $work_done = implode (' <br />', $service);//turn array into string $work = '<p>We provided the following services last time you visited: <br /> ' . $work_done . '</p>'; }else{ $service = NULL; $work_error = '<p class="error">Please choose at least one service.</p>';//error message } //if all OK, display information if($fname && $lname && $greeting && $email && $age && $gender && $use && $comments && $quality && $service){ echo '<p>' . $greeting . ' ' . $title . ' ' . $fname . ' ' . $lname . ' and thank you for your comments: <br /><br /><tt>' . $comments .'</tt> '. $work . $quality_ok . $age_message . ' We will reply to you at <i>'. $email . '</i></p>'; }else{//if it goes wahoonee shaped display error messages echo $title_error . $fname_error . $lname_error . $greeting_error . $age_error . $work_error .$quality_error . $comments_error . $email_error . '<p class="error">Please go back and complete the form.</p>';//concatenate error messages } ?> </body> </html>
×
×
  • Create New...