Jump to content
Larry Ullman's Book Forums

Wagtail

Members
  • Posts

    136
  • Joined

  • Last visited

  • Days Won

    1

Posts posted by Wagtail

  1. Hi Larry,

     

    thank you for the quick reply.

     

    I've gone through the book multiple times but cannot recall having seen such an example (returning information and then updating it with new values).

     

    In my example I've used $_POST but the value isn't coming from the database. I used <p>'.$row['name'] . ' to return the value from the database. The $_POST is for the new value.

     

    Must I use something like if (isset($_POST[$row['prop_name']])) as my conditional?

     

     

    Thank you.

  2. Hi Larry,

     

     

    do you mean like this?

    <p>change name: <input type="text" name="name" size="20" maxlength="60" value="'.$row['name'].'" /> </p>

    I've been trying for a few hours but haven't managed to get it right. If I use the above method then what happens to checking if the new value (name etc) has been set, validation etc.?

     

     

    I could also echo out the current name and then have an empty text input next to it, as in the following code. Can I print out html which includes a conditional as I'm trying to do?

    <?php
    
    
    
    $q = "SELECT name, location FROM table1 WHERE name = 'Homer Simpson' ";
        $r = @mysqli_query($dbc, $q);   
      
        $num = mysqli_num_rows($r);
        if ($num > 0) { 
            $row = mysqli_fetch_array($r, MYSQLI_ASSOC); 
    print'<h1>Change your details</h1>
    <form action="" method="post">
    	<p>'.$row['name'] . '<input type="text" name="name" size="20" maxlength="60" value="';
    if (isset($_POST['name'])) echo $_POST['name'];
    print'"  /> </p>
    	
    	<p><input type="submit" name="submit" value="Change Password" /></p>
    </form>';
    
    
    
    
    
        }
        
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {    
        
      
     $newname = mysqli_real_escape_string($dbc, trim($_POST['name']));   
    $q = "UPDATE table1 SET name='$newname' WHERE name='Homer Simpson' ";		
    			$r = @mysqli_query($dbc, $q);
    			
    			if (mysqli_affected_rows($dbc) == 1) {} // If it ran OK.
    
    				// Print a message.
    
    
    
    
    }
    
    ?>
    

    Thank you for your help!

  3. Hi Larry and forum members,

     

    I could please use some help as how to organize my code. What I'd like to do is retrieve some info using a SELECT query and then follow up with an UPDATE query.

     

    The problem I'm experiencing is the combining of the two.

     

    I have created a form with empty text inputs whereby I can update records in a database. Above each empty text input the current record must be displayed, which is retrieved using the SELECT query.

     

    So my form might look like this:

     

    Please use the form to update your details

     

    Current name: Homer Simpson

    // empty text input for new name

     

    Current telephone number: 4853090142

    // empty text input for new telephone number

     

    current location: Springfield

    // empty text input for new location

     

    etc....

     

    Please note that my form and queries are of course not complete. I'm just wondering how the code should be structured.

     

    Thank you in advance!

    <?php
    
    
    
    $q = "SELECT name, location FROM table1 WHERE name = 'Homer Simpson' ";
        $r = @mysqli_query($dbc, $q);   
      
        $num = mysqli_num_rows($r);
        if ($num > 0) { 
            $row = mysqli_fetch_array($r, MYSQLI_ASSOC); 
    print'<p class="name">'.$row['name'] . '</p>
    <p class="location">'.$row['location'] . '</p>';
        }
        
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {    
        
        
     $newname = mysqli_real_escape_string($dbc, trim($_POST['name']));   
    $q = "UPDATE table1 SET name='$newname' WHERE name='Homer Simpson' ";		
    			$r = @mysqli_query($dbc, $q);
    			
    			if (mysqli_affected_rows($dbc) == 1) {} // If it ran OK.
    
    				// Print a message.
    
    
    
    
    }
    
    ?>
    
    <h1>Please use the form to update your details</h1>
    <form action="" method="post">
    	<p>Current name: <input type="text" name="name" size="20" maxlength="60" value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>"  /> </p>
    
    	<p><input type="submit" name="submit" value="Change Password" /></p>
    </form>
    
  4. Hi Larry and forum members,

     

    I'm hoping someone could please help me out. I'd like to modify script 17.1 (from ch17, example message board) so that it works without the need for sessions. My non-forum website doesn't require any login/logout functionality, and anyone should be able to change the language (I plan on having a selection of 4 or 5 different languages).

     

    What I've done so far is replace all instances of $_SESSION['lid'] with $_GET['lid'] and modified <form action="forum.php" method="get"> to <form action="" method="get">. Something isn't working because I now receive an error: Undefined index: lid when I load the page.

     

    I've posted the modified code below.

    // Check for a new language ID...
    
    if ( isset($_GET['lid']) && 
    	filter_var($_GET['lid'], FILTER_VALIDATE_INT, array('min_range' => 1)) 
    	) {
    	 $_GET['lid'] = 1; // Default.
    	 }
    	
    
    // Get the words for this language:
    $q = "SELECT * FROM words WHERE lang_id = {$_GET['lid']}";
    $r = mysqli_query($dbc, $q);
    if (mysqli_num_rows($r) == 0) { // Invalid language ID!
    	
    	// Use the default language:
    	$_GET['lid'] = 1; // Default.
    	$q = "SELECT * FROM words WHERE lang_id = {$_GET['lid']}";
    	$r = mysqli_query($dbc, $q);
    	
    }
    
    // Fetch the results into a variable:
    $words = mysqli_fetch_array($r, MYSQLI_ASSOC);
    
    // Free the results:
    mysqli_free_result($r);
    ?>
    
    <?php 
    echo '<p>' . $words['home'] . '</p>
    <p>' . $words['about'] . '</p>';
    
    
    
    // For choosing a forum/language:
    echo '</b><p><form action="" method="get">
    <select name="lid">
    <option value="0">' . $words['language'] . '</option>
    ';
    
    // Retrieve all the languages...
    $q = "SELECT lang_id, lang FROM languages ORDER BY lang_eng ASC";
    $r = mysqli_query($dbc, $q);
    if (mysqli_num_rows($r) > 0) {
    	while ($menu_row = mysqli_fetch_array($r, MYSQLI_NUM)) {
    		echo "<option value=\"$menu_row[0]\">$menu_row[1]</option>\n";
    	}
    }
    mysqli_free_result($r);
    
    echo '</select><br />
    <input name="submit" type="submit" value="' . $words['submit'] . '" />
    </form></p>
        </td>
         
        <td valign="top" class="content">';
    ?>
     
    

    Thank you in advance!!!

  5. Hi everyone,

     

    I have seen a number of ecommerce and travel websites that include a filtering option, to narrow down the results displayed. For example, a page might display furniture (sofas). On that page will be a number of checkboxes whereby a user can select one or more checkboxes (colour, fabric, style, price etc) and the results will be updated accordingly.

     

    Is this very complicated to code? My page would include pagination.

     

    Could someone please advise me as to how to proceed with this project?

     

    Thank you in advance.

  6. Hi Larry,

     

    thank you for getting back to me!

     

    I'm a bit confused as to what I should do.

     

    If I only include this for my email:

    <input type="text" name="email" size="30" maxlength="80" value="<?php if (isset($scrubbed['email'])) echo $scrubbed['email']; ?>" />
    

    then where do I add the error message you gave to me in your first reply?

    <?php if (isset($errors['email'])) echo $errors['email'];?>
    

    I would like to have the error message pop-up next to the name of the specific form input, which is why I put it between the span tags.

    <p>Email Address:
    <span><?php if (empty($scrubbed['email'])) echo $no_email;?></span>
    </p>
    <input type="text" name="email" size="30" maxlength="80" value=
    "<?php if (isset($scrubbed['email'])) echo filter_var($scrubbed['email'], FILTER_VALIDATE_EMAIL); ?>" /> 
    
    

    And what about running ($scrubbed['email']) through a filter?

     

     

    You also asked me about my last question. In your book on p407, ch13 security methods, you describe the following code:

    if (!empty($scrubbed['name']) && !empty($scrubbed['email']) && !empty($scrubbed['comments']) ) {
    	
    		// Create the body:
    		$body = "Name: {$scrubbed['name']}\n\nComments: {$scrubbed['comments']}";
    
    

    From my understanding this means that if ($scrubbed['name']), ($scrubbed['email']) etc are all not empty, then the values can be assigned to the $body variable. In my form all of the values would need to be not only not empty but have also been run through an appropriate filter. Should I therefore have the following in my code?

    	if (!empty($scrubbed['email']) && filter_var($scrubbed['email'], FILTER_VALIDATE_EMAIL)
    && !empty($scrubbed['name']) && filter_var($scrubbed['name'], FILTER_SANITIZE_STRING))
      {
    
    
    

    Herewith my code:

    <?php # Script 13.1 - email.php #2
    // This version now scrubs dangerous strings from the submitted input.
    
    // Check for form submission:
    
    
    
    $errors = array();
    
    
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    
    if (!isset($scrubbed['name']) || !filter_var($scrubbed['name'], FILTER_SANITIZE_STRING)) {
        $errors['name'] = 'Please enter a name.';
    }
    
    
    
    if (!isset($scrubbed['email']) || !filter_var($scrubbed['email'], FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = 'Please enter a valid email address.';
    }
    
    	/* The function takes one argument: a string.
    	* The function returns a clean version of the string.
    	* The clean version may be either an empty string or
    	* just the removal of all newline characters.
    	*/
    	function spam_scrubber($value) {
    
    		// List of very bad values:
    		$very_bad = array('to:', 'cc:', 'bcc:', 'content-type:', 'mime-version:', 'multipart-mixed:', 'content-transfer-encoding:');
    	
    		// If any of the very bad strings are in 
    		// the submitted value, return an empty string:
    		foreach ($very_bad as $v) {
    			if (stripos($value, $v) !== false) return '';
    		}
    	
    		// Replace any newline characters with spaces:
    		$value = str_replace(array( "\r", "\n", "%0a", "%0d"), ' ', $value);
    	
    		// Return the value:
    		return trim($value);
    
    	} // End of spam_scrubber() function.
    
    	// Clean the form data:
    	$scrubbed = array_map('spam_scrubber', $_POST);
    
    	// Minimal form validation:
    	if (!empty($scrubbed['email']) && !empty($scrubbed['name']) ) {
    	
    		// Create the body:
    		$body = "Name: {$scrubbed['name']}\n\nComments: {$scrubbed['comments']}";
    
    		// Make it no longer than 70 characters long:
    		$body = wordwrap($body, 70);
    	
    		// Send the email:
    		mail('your_email@example.com', 'Contact Form Submission', $body, "From: {$scrubbed['email']}");
    
    		// Print a message:
    		echo '<p><em>Thank you for contacting me. I will reply some day.</em></p>';
    		
    		// Clear $scrubbed (so that the form's not sticky):
    		$scrubbed = array();
    		
    	
    	} 
    	
    } // End of main isset() IF.
    
    // Create the HTML form:
    ?>
    <p>Please fill out this form to contact me.</p>
    <form action="email.php" method="post">
    
    	
    	<p>Name:
    	<span><?php if (isset($errors['name'])) echo $errors['name'];?></span>
    	</p>
    	<input type="text" name="name" size="30" maxlength="60" value=
    	"<?php if (isset($scrubbed['name'])) echo filter_var($scrubbed['name'], FILTER_SANITIZE_STRING); ?>" />
    	
    	
    	<p>Email Address:
    	<span><?php if (isset($errors['email'])) echo $errors['email'];?></span>
    	</p>
    	<input type="text" name="email" size="30" maxlength="80" value=
    	"<?php if (isset($scrubbed['email'])) echo filter_var($scrubbed['email'], FILTER_VALIDATE_EMAIL); ?>" />
    	
    	
    	<p><input type="submit" name="submit" value="Send!" /></p>
    </form>
    </body>
    </html>
    

    Thank you again for your help.

  7. Hi Larry,

     

    thank you so much for replying! Please excuse the late reply.

     

    So I tried the code you provided but I'm still experiencing some issues.

     

    Should the email code look like this?

     

    <p>Email Address:

    <span><?php if (isset($errors['email'])) echo $errors['email'];?></span>

    </p>

    <input type="text" name="email" size="30" maxlength="80" value=

    "<?php if (isset($scrubbed['email'])) echo filter_var($scrubbed['email'], FILTER_VALIDATE_EMAIL); ?>" />

     

    If I enter a valid email address and press send, the error message still remains. Also, how would I change the following code, so that everything is scrubbed, filtered and validated before the body of the email is created?

     

    // Minimal form validation:

    if (!empty($scrubbed['email']) && !empty($scrubbed['name']) ) {

      // Create the body:

      $body = "Name: {$scrubbed['name']}\n\nComments: {$scrubbed['comments']}";

     

    Thank you. I appreciate your help!

  8. Hi everyone,

    I bought the book PHP and MySQL for Dynamic Web Sites, but I need some help with regards to my form. I'm hoping someone could please help me – thanks!

    This is a contact form that gets sent to an email address. I would like to combine the spam_scrubber() function from script 13.1 with the filter extensions. I also added some error messages that get displayed if the form isn't filled in.

    There is a problem with the email. If I submit the form but the email input isn't filled in, the error message pops up – as it should. If I add some random text, and submit the form, the text disappears. Presumably because the filter extension is working properly? I would like to display a message such as “invalid email” if someone tries to submit the form without a valid email address.

    In other words, I need two error messages for my email:
    1) if the email input is empty
    2) if the email input doesn't contain a valid email address.

    Currently my email error variable looks like this (if the input is empty and the form is submitted):
    <span><?php if (empty($scrubbed['email'])) echo $no_email;?></span>

    I tried to add code that would display an “invalid email” message if the value has been sent through the filter extension. Something like:
    $validemail = filter_var($scrubbed['email'], FILTER_VALIDATE_EMAIL);
      if ($validemail) {
        echo $invalid_email;
      }

    I'm still learning PHP so the above code did not work.

    Thank you for your help!


    Here is the code:
    PS: I left out the scrubber function code to save space.

    // I initialized the some variables for the error messages
    $no_name = $no_email  = "";

    // Check for form submission:
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // I assigned messages to the error variables
    $no_name = "You forgot to enter your name";
    $no_email = "You forgot to enter your email";

    // scrubber begins
        function spam_scrubber($value) {

            
            // Clear $scrubbed (so that the form's not sticky):
            $scrubbed = array();

    // cleared error messages after form has been submitted
            $no_name = "";
                            $no_email = "";
        
        }
        
    } // End of main isset() IF.




    // Create the HTML form:
    ?>
    <p>Please fill out this form to contact me.</p>
    <form action="email.php" method="post">
        <p>Name:
        <span><?php if (empty($scrubbed['name'])) echo $no_name;?></span>
        </p>
        <input type="text" name="name" size="30" maxlength="60" value=
        "<?php if (isset($scrubbed['name'])) echo filter_var($scrubbed['name'],     FILTER_SANITIZE_STRING); ?>" />
        
        <p>Email Address:
        <span><?php if (empty($scrubbed['email'])) echo $no_email;?></span>
        </p>
        <input type="text" name="email" size="30" maxlength="80" value=
        "<?php if (isset($scrubbed['email'])) echo filter_var($scrubbed['email'], FILTER_VALIDATE_EMAIL); ?>" />
        
       

×
×
  • Create New...