Jump to content
Larry Ullman's Book Forums


  • Posts

  • Joined

  • Last visited

Posts posted by peppericious1

  1. I have made a few slight changes to the login script in Ch 18. One change is to have a last_login field updated when a user logs in.


    The script works as I want it to. However, the last_login (type DATETIME) column in my db is not updating.


    Could anyone suggest why this col is not updating? Thanks in advance. Code is below...


    require ('includes/config.inc.php');
    $page_title = "Log-in";
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $errors = array();
    // Validate the email address:
    if (!empty($_POST['email'])) {
     $e = mysqli_real_escape_string($dbc, $_POST['email']);
    } else {
     $e = FALSE;
     $errors[] = 'Please enter a valid email address.';
    // Validate the password:
    if (!empty($_POST['pass'])) {
     $p = mysqli_real_escape_string($dbc, $_POST['pass']);
    } else {
     $p = FALSE;
     $errors[] = 'Please enter a password.';
    if ($e && $p) { // If everything's OK.
     // Query the database:
     $q = "SELECT id, first_name, level FROM users WHERE (email='$e' AND password=SHA1('$p')) AND active =''";
     $r = mysqli_query($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
     if (mysqli_num_rows($r) == 1) { // A match was made.
    	 // Register the values:
    	 $_SESSION = mysqli_fetch_array($r, MYSQLI_ASSOC);
    	 $id = $_SESSION['id'];
    	 // set last login date and time
    	 $q = "UPDATE users SET last_login = NOW() WHERE id = $id";
    	 $r = mysqli_query($dbc, $r) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
    	 // Redirect the user:
    	 $url = BASE_URL . 'index.php'; // Define the URL.
    	 header("Location: $url");
    	 exit(); // Quit the script.
     } else { // No match was made.
    	 echo '<div id="lesson_wrap">
    	 <h2 class="top error">Login failed.</h2>
    	 <p class="error">No such username/password combination found.</p>
    	 <p>Please <a href="login.php">try again</a>.</p>
    } else { // If one of the data tests failed.
     echo "<div id='lesson_wrap'>
    		 <div id='errors_holder'>
    		 <h2>Oops, wait a minute...</h2>
     foreach ($errors as $error) {
    	 echo "<li class='error'>$error</li>";
    	 <div id='form_holder'>
     <form name='signup' id='signup' method='post' action='' >
    	 <label for='email'>Email address</label>
    	 <input type='text' name='email' id='email' value='<?php if(isset($e)) { echo $e; }?>'/>
    	 <label for='pass'>Password</label>
    	 <input type='password' name='pass' id='pass' value=''/>
    	 <input type='submit' name='submit' value='Log in' />
    } else { // End of SUBMIT conditional.
    <div id='lesson_wrap'>
    <h2 class='top'>Log in.</h2>
    <p><em>(Note: your browser must allow cookies in order to log in.)</em></p>
    <div id='form_holder'>
     <form name='signup' id='signup' method='post' action=''>
    	 <label for='email'>Email address</label>
    	 <input type='text' name='email' id='email' value=''/>
    	 <label for='pass'>Password</label>
    	 <input type='password' name='pass' id='pass' value=''/>
    	 <input type='submit' name='submit' value='Log in'/>
    <?php include ('includes/footer.php');

  2. Sorry to not fully answer your question. I was kind of assuming that you knew how to make the actual assignment.

    As an example, if you have a div in your HTML with an ID of "overlay", you could do something like the following:


    var overlayDiv = document.getElementById('overlay');

    overlayDiv.style.height = document.body.clientHeight;


    That should work.


    That's great, HartleySan, thanks. I'll give it a go right away and if I'm still in trouble, will post back.


    p.s. I see from your signature that you're in Japan... I lived in the south of Honshu for 2 years back in the early 90s… a wonderful time. Mata ato de, ne!

  3. Chapter 9 does explain how to set CSS properties using JavaScript. Also, just to confirm, have you read the first eight chapters?


    ... so that's what I have to do - to change the height of the modal mask div by referring to document.body.clientHeight as HartleySan suggested, is that right?


    No, I have only flicked through the table of contents thus far as I only received your book on Thursday of last week. I was working on the project above before the book arrived and must get it off my desk before I can dig in to the book...

  4. The following will give you the height of the entire page, regardless of the browser:




    Simply set the height of the overlay div to that, and you're good to go.


    Thanks, HartleySan, for your kind comments about the site and for your help which is very informative.


    However, when you say 'Simply set the height of the overlay div...', could you tell me exactly how I should do that?... As yet, I have not done *any* js coding (hence my purchase of Larry's book), so a couple of pointers would be much appreciated.



  5. Hi Larry and forum users.


    I just got 'Modern Javascript' and am eager to get stuck into it. I need to implement a modal dialog quickly for a project I'm working on, however, and am having an issue I don't know how to resolve.


    The modal dialog as discussed in ch.9 contains just a little text. Mine, however, will be used to display a comprehensive list of terms and conditions of several hundred words.


    The problem is that when the user scrolls the page down through the terms and conditions, the light-grey modal mask background does not expand. You can see the problem here.


    What can I do to get the mask to fill the entire browser window when the user scrolls down?


    And one more thing... What if the user has javascript turned off. Can I simply link to a page in the href tag as a fallback?...


    Thanks in advance for your help.

  6. Have you looked at the source code for that page to confirm it's being set correctly?


    You should dump the contents of the information sent by paypal to your ipn script into a text file. This will enable you to see which conditions are met and whether your ipn script gets to the part where the sql query should be executed.


    If it does then you'll have to go through the standard sql debugging to see where the error is.


    i know the fee is being set correctly because it determines the price charged when I get to paypal and that amount is correct when I get to paypal.


    Regarding your suggestion to dump the contents returned by Paypal to the ipn script into a text file, how would I do that, exactly? It's my first time doing a Paypal implementation so I'm brand new to this.


    I've been very frustrated trying to figure out what POST variables are returned by PayPal to my ipn script. It returns lots of variables - in addition to those associated with my own button, right?... I've tried to find out from Paypal's own documentation but haven't been able to figure it out....

  7. I'm doing an application whereby parents will be registering their kids in an orchestra. The cost of registration is a sliding cost if there's more than just one kid in a given family registering for the orchestra. So, 1st kid 100 euros, 2nd kid 80 euros, 3rd and subsequent kids 60 euros, etc.


    The cost of registration is calculated in advance, before the registrant gets to the page with the paypal 'Pay Now' button, and is stored in a 'fee' session variable. I'm then passing the value of $_SESSION['fee'] to the paypal button... or at least that is my intention.


    My ipn.php script - adapted from ch. 6 of Larry's book - is this:


    $req = 'cmd=_notify-validate';
    // Add each received key=value pair to the request:
    foreach ($_POST as $key => $value) {
    $value = urlencode(stripslashes($value));
    $req .= "&$key=$value";
    // Open a socket connection to PayPal:
    $fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30); // Test
    //$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30); // Live
    if (!$fp) { // If we couldn't connect, send an email:
    trigger_error('Could not connect for the IPN!');
    } else { // Send the request to PayPal:
    $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
    $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
    fputs ($fp, $header . $req);
    // Read in the response:
    while (!feof($fp)) {
     $res = fgets ($fp, 1024);
     if (strcmp ($res, "VERIFIED") == 0) {  
      // Check for the right values:
      if ( isset($_POST['payment_status'])
    && ($_POST['payment_status'] == 'Completed')
    && ($_POST['receiver_email'] == 'hugh.n_1327507957_biz@gmail.com')
    && ($_POST['mc_gross'] == $_SESSION['fee'])
    && ($_POST['mc_currency']  == 'EUR')
    && (!empty($_POST['txn_id']))
      ) {  
    // Need the database connection now:
    // Check for this transaction in the database:
    $txn_id = mysqli_real_escape_string($dbc, $_POST['txn_id']);  
    $q = "SELECT id FROM orders WHERE transaction_id='$txn_id'";
    $r = mysqli_query ($dbc, $q);
    if (mysqli_num_rows($r) == 0) { // Add this new transaction:  
     $uid = (isset($_POST['custom'])) ? (int) $_POST['custom'] : 0;
     $status = mysqli_real_escape_string($dbc, $_POST['payment_status']);
     $amount = (float) $_POST['mc_gross'];
     $q = "INSERT INTO orders (user_id, transaction_id, payment_status, payment_amount) VALUES ($uid, '$txn_id', '$status', $amount)";
     $r = mysqli_query ($dbc, $q);
     if (mysqli_affected_rows($dbc) == 1) {
     } else { // Problem inserting the order!
      trigger_error('The transaction could not be stored in the orders table!');
    } // The order has already been stored!
      } // The right values don't exist in $_POST!
     } elseif (strcmp ($res, "INVALID") == 0) {
      // log for manual investigation
    } // End of the WHILE loop.
    // Close the connection:
    fclose ($fp);
    } // End of $fp IF-ELSE.



    The code for the page containing the button which takes registrants to paypal is this:


    $page_title = "CYO Registration | Payment";
     if($_SESSION['form3done'] != '1') {
      // echo 'this page accessed in error
       </div> <!-- c1 content closer -->
      </div> <!-- c1 closer -->
     <div id="c2">
       <div class="content">
    	 <p>You have accessed this page in error.</p>
       </div> <!-- c2 content closer -->
      </div> <!-- c2 closer -->
    } else {
    $uid = $_SESSION['uid'];
    $fee = $_SESSION['fee'];
    </div> <!-- c1 content closer -->
    </div> <!-- c1 closer -->
     <div id="c2">
    <div class="content">
     // registration period
      $thisyear = date('Y');
     $nextyear = date('Y')+1;
      <h1>CYO Registration Fee, <?php echo $thisyear . '–' . $nextyear; ?></h1>
      <p>A fee of <strong>€<?php echo $_SESSION['fee']?></strong> is now payable to complete your registration for CYO. Please click the button below to proceed.</p></p><em>(You will be momentarily redirected to PayPal where you can make your secure payment. You will then be returned here, on completion of your payment.)</em></p>
      <table width="100%" style='border: 1px solid gray;padding: 4px 0 0 10px;border-radius: 5px;margin-top: 30px;'>
    	  <td width="80%" style='font-weight:bold;'>CYO Registration fee for <?php echo stripslashes($_SESSION['firstname']) . ' ' . stripslashes($_SESSION['lastname']) . " (" . $uid . ")";?></td>
    	 <td width="20%">
    		  <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
    			<input type="hidden" name="cmd" value="_xclick">
    			<input type="hidden" name="custom" value="<?php echo $uid;?>">
    			<input type="hidden" name="business" value="ZRTUX4VF273MJ">
    			<input type="hidden" name="lc" value="GB">
    			<input type="hidden" name="item_name" value="Reg">
    			<input type="hidden" name="amount" value="<?php echo $fee;?>">
    			<input type="hidden" name="currency_code" value="EUR">
    			<input type="hidden" name="button_subtype" value="services">
    			<input type="hidden" name="no_note" value="1">
    			<input type="hidden" name="no_shipping" value="1">
    			<input type="hidden" name="rm" value="1">
    			<input type="hidden" name="return" value="https://www.corkyouthorchestra.ie/registration_complete.php">
    			<input type="hidden" name="cancel_return" value="https://www.corkyouthorchestra.ie/cancel_purchase.php">
    			<input type="hidden" name="bn" value="PP-BuyNowBF:btn_paynow_SM.gif:NonHosted">
    			<input type="image" src="https://www.sandbox.paypal.com/en_GB/i/btn/btn_paynow_SM.gif" border="0" name="submit" alt="PayPal — The safer, easier way to pay online.">
    			<img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
    </div> <!-- c2 content closer -->
    </div> <!-- c2 closer -->



    My db is not being updated however. My orders table is this:


     `id` int(10) unsigned NOT NULL auto_increment,
     `user_id` int(10) unsigned default NULL,
     `transaction_id` varchar(19) NOT NULL,
     `payment_status` varchar(15) NOT NULL,
     `payment_amount` decimal(6,2) unsigned NOT NULL,
     `payment_date_time` timestamp NOT NULL default CURRENT_TIMESTAMP,
     PRIMARY KEY  (`id`),
     KEY `user_id` (`user_id`)


    If anyone could tell me why my db is not being updated, I would greatly appreciate it.



  8. Hi Larry and forum users.


    I have a problem that I can't resolve.


    I have set up my pagination script to display 5 blog posts per page. (I'm working on a local server at present so unfortunately I can't provide a link to the page). Currently, there are 15 blog posts in my db. Obviously, the pagination numbers at the bottom of my page should show three digits, '1', '2', and '3', with each page showing 5 posts. The thing is, I see four digits: '1', '2', '3'... and '4'.


    When I click '1', I see the first 5 records and "index.php?s=0&p=4" is displayed in my url. Clicking '2' shows me records 6 to 10 ("index.php?s=5&p=4" displays in the url), '3' shows 11 to 15 ("index.php?s=10&p=4" displays in the url)... and clicking '4' takes me to a page displaying no posts at all.

    When I add a sixteenth post, no problem. Clicking '4' shows a page with 1 post, as should be the case, and my URL shows "index.php?s=15&p=4").


    So, in summary, the problem seems to arise when the number of records is evenly divisible by the number of records held in the $display variable. When the total number of records is not evenly divisible, the problem resolves itself.


    Can anyone figure out what might be wrong? I'm sure it's something small... I'd really appreciate your help. My code is below (most of which is directly from your book, Larry, on pp 318, 319):


    $display = 5;
    // determine the number of pages
    if (isset($_GET['p']) &&
    is_numeric ($_GET['p'])) { // already determined
     $pages = $_GET['p'];
     } else { // must be determined
      $q = "
      SELECT COUNT(post_id)
      FROM lfbp_blog
      $r = @mysqli_query ($dbc, $q); // Run the query.
      $row = mysqli_fetch_array ($r, MYSQLI_NUM);
      $total_records = $row[0];
      // Calculate the number of pages that will be required to display all records
      if ($total_records > $display) { // means that more than 1 page will be required
      $pages = ceil($total_records/$display); // ceil function returns division result rounded upwards to nearest integer
      } else {
      $pages = 1;
    } // end if
     // Determine where in the db to start returning results
     if (isset($_GET['s']) &&
      is_numeric($_GET['s'])) {
    $start = $_GET['s'];
      } else {
    $start = 0;
    // start of news
    // find blog posts to display
    // end of news-->
    // show links to other pages, if necessary
      if ($pages > 1) {
    echo '<p>';
    $current_page = ($start/$display) + 1;
    // if it's not the first page, make a Previous button
    if ($current_page !=1) {
     echo '<a href="index.php?s=' .
     ($start - $display) . '&p=' . $pages . '">Newer posts</a> ';
    // Make all the numbered pages
    for ($i = 1; $i <= $pages; $i++) {
     if ($i != $current_page) {
      echo '<a href="index.php?s=' . (($display * ($i - 1))) . '&p=' . $pages . '">' . $i . '</a> '; }
      else {
       echo $i . ' ';
    } // end of FOR loop
    // If it's not the last page, make a Next button
    if ($current_page != $pages) {
     echo '<a href="index.php?s=' . ($start + $display) . '&p=' . $pages . '">Older posts</a>';
    echo '</p>'; // Close the paragraph on the pagination line of content
      } // End of the links section

  9. Rob, I'm still not getting this to work...


    I wasn't exactly sure what you meant by this....

    ... and return the sanitized value if $input_name triggers else in your empty conditional.


    I altered my function so that it now looks like:

    function validate_text_input($input_name, $err_msg) {
    global $dbc;
    global $errors;
    if (empty($_POST[$input_name])) {
     $errors[] = $err_msg;
      } else {
    if (get_magic_quotes_gpc()) {
     $input_name = mysqli_real_escape_string($dbc, stripslashes(trim($_POST[$input_name])));
    else {
     $input_name = mysqli_real_escape_string($dbc, trim($_POST[$input_name]));
      return $input_name;


    ... but the else part of the conditional isn't working for me. I'm still getting this error…

    : Undefined variable: post_title...



    Can you see what I'm doing wrong?.... Thanks in advance if you can help.

  10. Yes, scope issues.


    mysqli_real_escape_string requires the database connection, so you'll either need to pass the connection into the function or make $dbc global.


    As it stands you're not returning any values ($errors, $input_name) so they are not accessible outside of the function. Again you could make $errors global and return the sanitized value if $input_name triggers else in your empty conditional.


    Thanks for this.


    I didn't want to put the connection in the function as I'd have been opening and closing it every time I called the function, so I'll make $dbc global.


    I see what you're saying about returning values... I'll do as you advise regarding making $errors global and returning the sanitised $input_name. I'm only just starting out with functions but am quickly seeing their potential...

  11. Hi Larry,


    I've quite a few forms and I seem to regularly copy and paste this bit of code:

    if (empty($_POST['post_title'])) {
    	 $errors[] = 'You forgot to enter a post title.';
    	} else {
    	 if (get_magic_quotes_gpc()) {
    	  $post_title = mysqli_real_escape_string($dbc, stripslashes(trim($_POST['post_title']))); }
    	 else {
    	  $post_title = mysqli_real_escape_string($dbc, trim($_POST['post_title']));


    ... so I put this function together in a functions.php file:

    function validate_text_input($input_name, $err_msg) {
    if (empty($_POST[$input_name])) {
     $errors[] = $err_msg;
      } else {
    if (get_magic_quotes_gpc()) {
     $input_name = mysqli_real_escape_string($dbc, stripslashes(trim($_POST[$input_name]))); }
    else {
     $input_name = mysqli_real_escape_string($dbc, trim($_POST[$input_name]));


    ... and am including it like this:



    ... and calling within the rest of my code like this:

    validate_text_input('post_title', 'Please enter a title for your post.');
    validate_text_input('post_subtitle', 'Please enter a subtitle for the blog post.');
    validate_text_input('post_body', 'Please enter the body of the blog post.');


    ... in my form, that input is like this:

    <form name="form" method="post" action="">
      <label for="title">Post Title</label>
      <input type="text" name="post_title" id="post_title" value="<?php if((isset($_POST['post_title'])) && (!empty($errors))) { echo $_POST['post_title']; }?>" />
      <!-- other inputs -->
      <input type="submit" name="submit" value="Add Blog Post" />


    Now, if I enter nothing at all in the post_title field and submit, the validation works and I see the error. However, if I do put something in the post_title field and submit, I get this error:

    Notice: Undefined variable: post_title in /…/…/…/.../add_blog_post.php on line 42


    I can't figure out what I'm doing wrong. Maybe I've been looking for it for too long... Is it something to do with the scope of the $input_name variable within the function? If that is the case, how do I fix the problem? I should add that I've only just started using functions.


    Any suggestions and/or help would be appreciated.


    Thanks in advance.

  12. Hi, Larry, and forum users.


    I suspect that the message:

    Your browser must allow cookies in order to log in



    ... would turn away a significant number of visitors, if for no other reason than the fact that a lot of people think (rightly or wrongly) that cookies are inherently malicious.


    How would I modify login.php so that cookies are not required?


    Thanks in advance.




    p.s. a sincere thank you, Larry, for the fantastic books you write. I've learned - and continue to learn - so much from them.

  • Create New...