Jump to content
Larry Ullman's Book Forums

Deaddog

Members
  • Posts

    47
  • Joined

  • Last visited

Posts posted by Deaddog

  1.  

    Well, to be clear, this forum does not do that. "Translating Geek to English" is a marketing phrase I use. Complaining that the forums didn't do that for you is akin to complaining that your new Nikes didn't make you able to "just do it".

     

    You got me there,  I had that one coming :).  I thought you went sort of easy on me, but you added a little salt in the wound at the end there with:

     

    I'll mock something up when I get a spare 30 minutes in the next week or so and I'll post that here.

     

    It must be great to just whip up something like this in 30 minutes.  A lifetime of practice I suppose.

     

     

    One thing to note here is that OOP is being used in 3 ways in this example, which adds to the complexity. There are classes defined for each database table--Page and User, if I recall correctly. Then OOP is being used by tapping into PDO for the database interactions. Then OOP is used with HTML_QuickForm2 to create and validate the forms.

     

    In my case, I spent a fair amount of time installing and getting the hang of the quick_form2, and really like it.  Hopefully your example will sort of align with the code that the book uses.    I'm really looking forward to your example, but take your time there is no big rush.  I mean if you have to use 45 minutes....by all means.  All joking aside, thanks so far.

  2. This forum claims it will "translate geek into English", but I have to say in this case it has gone from geek to just another version of geek. 

     

    Unfortunately, on this specific oop forum (for this book), I have not read any success stories of someone implementing a registration form using oop techniques.  The forum user senso attempted it, but never finished or never re-posted.  I assume that user gave up due to frustration.  I don't plan on doing that, I haven't spent hundreds of hours over the years and purchase four Ullman books to quit.

     

    The procedural way from PHP and MySQL for Dynamic Web Sites is what I have used for all my websites up until now.  That book had a great example of user registration.  I bought PHP Advanced and OOP in order to take it to the next level, but this is not happening.   The book does not contain a registration form example.  I'm trying to pursue, not just posting and expecting to be spoon fed the answers.   I thought I had made progress earlier in this post by checking for existing email addresses and username, but I was wrong. 

     

    I appreciate all the help I have received on this forum, it's a great forum to compliment a lot of excellent books.  In this case, Larry or one of the other experts here, can you please post an example of a registration form code?   I need someone to show a good example of a registration form using the oop techniques from Chapter 9.   I've been working on this for one month, I'm learning a lot about oop, but still cannot get the  registration form to work.   Mainly because I can't get the ->rowCount() to work in order to check for existing users.

  3. Step 1) Beg, borrow, steal, buy, fabricate or otherwise obtain a rubber duck (bathtub variety)

    Step 2) Place rubber duck on desk and inform it you are just going to go over some code with it, if that's all right.

    Step 3) Explain to the duck what your code is supposed to do, and then go into detail and explain your code line by line

    Step 4) At some point you will tell the duck what you are doing next and then realise that that is not in fact what you are actually doing. The duck will sit there serenely, happy in the knowledge that it has helped you on your way.

    Note: In a pinch a coworker might be able to substitute for the duck, however, it is often prefered to confide mistakes to the duck instead of your coworker.

     

     

    When I remove the getValue() then the error is number of bound variables does not match number of tokens.

    The duck just told me I was crazy.

  4. Continuing on, the part of the registration form that checks the username and email now works, using the first prepared statement.   The next part is to insert the data which is, usertype, *username, *email, *pass, active, dateAdded.   Those marked with * come from quickform2.  usertype, active (random activation code) are giving me trouble.  Below is the code I have tried:

    $q = 'INSERT INTO users (usertype, username, email, pass, active, dateAdded) VALUES (:usertype, :username, :email, pass=SHA1(:pass), :active, NOW()';
    		$usertype = 'publicUser';
    		$active = md5(uniqid(rand(), true));
    		$stmt = $pdo->prepare($q);
    		//$pdo->bindParam(':ustertype',$usertype);
    		$stmt->bindValue(':active',$active);
    		$stmt->bindValue(':usertype',$usertype);
    		$r = $stmt->execute(array(':usertype'=>$usertype->getValue(),':username' =>$username->getValue(), ':email' =>$email->getValue(), ':pass' =>$password->getValue(),':active'=>$active->getValue())); 
    

    The error I receive is, Call to a member function getValue() on a non-object .  Despite the fact that there are many tutoriols out there on the net I can't find anything that seems to work in my case.   How do I get this error to go away to make the insert?

  5. I'm using var_dump($r) to try and troubleshoot this.

    Why does this query return boolean false? 

    (regardless of what values I put in the form)

     if ($form->validate()) {
    		$q = "SELECT COUNT(email) FROM users WHERE username=$username OR email=$email";
    		$r = $pdo->query($q);
    

    And this query return an object?

    (This works fine, there is no form input)

    //This is from Chapter 9, index.php)
    try{
    	$q = 'SELECT id, title, content, DATE_FORMAT(dateAdded, "%e %M %Y") AS dateAdded FROM pages ORDER BY dateAdded DESC LIMIT 1';
    	$r = $pdo->query($q);
    

    And this query return only boolean true?

        if ($form->validate()) {
    		
    		$q = 'SELECT COUNT(email) FROM users WHERE username=:username OR email=:email';
    		$stmt = $pdo->prepare($q);
    		$r = $stmt->execute(array(':username'=>$username->getValue(), ':email'=>$email->getValue()));
    

    I'm just not getting this.   For the first and the last examples, I've tried loads of different combinations of if($r && $r->rowCount() == 0){,

     but nothing seems to work.   I've also tried if($r ->fetchColumn() == 0){  ...

     

    On a positive note, I did manage to learn a bit more about quickforms2, regex and compare, very nice.

     

    I need assistance to get this registration form email and username check through my thick head!  

  6. So,  I have tried to use the getValue() like this, however, it produces two errors:

    • Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens and
    • Call to a member function fetchColumn() on a non-object''

     

    Why?
     

    $q = 'SELECT COUNT(email) FROM users WHERE email=:email';
    $stmt = $pdo->prepare($q);
    $r = $stmt->execute(array(':username'=>$username->getValue(), ':email'=>$email->getValue()));
    if ($r->fetchColumn() > 0){
    

    I know you said in your previous post to use $pdo->query($q), but I'm struggling to figure out how to do this and at the same time get the input values from the form...So, here I am stuck!

  7. Thanks for the help so far.

     

    Why does A not work with $r->rowCount and B work? 

     

    A is my attempt at making the registration form verify email addresses previously registered, email=:email comes from user input using QuickForms2 

    B is from Chapter 9, index.php.

     if ($form->validate()) {
    		//A) This does not work with $r->rowCount($q): $q = 'SELECT COUNT(*) FROM users WHERE email=:email';
    		//B) This works with $r->rowCount($q):  $q = 'SELECT id, title, content, DATE_FORMAT(dateAdded, "%e %M %Y") AS dateAdded FROM pages ORDER BY dateAdded DESC LIMIT 1';
    		$r = $pdo->query($q);
    		//check that some rows were returned.
    		if($r && $r->rowCount() > 0){
    

    Here is the form code:

    require('HTML/QuickForm2.php');
    $form = new HTML_QuickForm2('RegistrationForm');
    //Add the desired username field.
    $username = $form->addElement('text', 'username');
    $username ->setLabel('Desired Username');
    $username ->addFilter('trim');
    $username ->addRule('required','Please choose your desired username.');
    //Add the email address field.
    $email = $form->addElement('text','email');
    $email->setLabel('Email');
    $email->addFilter('trim');
    $email->addRule('required','Please enter your email address.');
    //Add the password field.
    $password =$form->addElement('password','pass');
    $password->setLabel('Password');
    $password->addFilter('trim');
    $password->addRule('Required','Please create a password.');
    
  8. So I'm trying to make a simplified version of checking the email against the existing users, see code snippet: (For registration purposes).

    if($_SERVER['REQUEST_METHOD']=='POST'){
    		// Validate the form data:
        if ($form->validate()) {
    		$results = $pdo->query('SELECT id FROM users WHERE email=:email'); //Review page 262
    		if ($results->rowCount() == 1){
    		echo 'Sorry, that username or email is previously registered!';
    		include('includes/header.inc.php');
    		include('views/register.html');
    		include('includes/footer.inc.php');
    		exit();
    
    

    I keep getting the error, "Call to a member function rowCount() on a non-object..."  I'm following or at least think I'm following the book, referring to  Chapter 8, page 262 in my book.  $results->rowCount() should be equivalent to mysqli_num_rows, but I'm not getting it to work. 

    What am I doing wrong?

    Jason

  9. For the sake of simplicity, I think I'm leaning towards adding the active to the user table.

    I'm going to make a page called registration.php.  The script will check the email against the users table using a prepared statement.  If that email is not previously registered it will insert the name, email, password and activation code on a second prepared statement.  Is this basically what needs to happen? 

     

    So the first hurdle is getting the oop/pdo equivalent of this:

    $q = "SELECT user_id FROM users WHERE email='$e'";
    	$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
    	
    	if (mysqli_num_rows($r) == 0) { //Available.
    		//Create the activation code.
    		$a = md5(uniqid(rand(), true));
    
  10. This will be my first attempt to really dig into oop on my own, without copying the code directly from the book.  It seems very overwhelming.

     

    Using the CMS from Chapter 9, I will try to expand on the registration form in order to add an activation code.  The goal is that when a new user registers, an activation link will be sent by email.  I know this procedural method from one of Larry's previous books.

     

    For the oop, I really need some help to get things started in the right direction. 

    So far, I've added a column to the users table called active.  A char(32), default NULL.

    Added an attribute $protected active = null to class User().

    -Made a registration form with the following fields: desired username, email, password and retype password fields.

     

    Any general advice on how I should proceed would be very helpful.

     

     

  11. The answer to this is simple:

    Took the dog for a walk, came home and re-read through chapter 8, the part where it says "Note that this does assume that the classes and class files use the same exact names( minus the extensions)." 

     

    So I just changed the file classes/page.php to classes/Page.php.

     

    Such details.  Strange that it worked fine on local machine with the lowercase page.php, but not on the live server. 

     

    Problem solved. :)

  12. I don't understand what is going on.  The CMS site works fine on local server, but when on the live site the following error occurs:

     

    Warning: require(classes/Page.php) [function.require]: failed to open stream: No such file or directory in /home/folder_name/public_html/51/includes/utilities.inc.php on line 4

    Warning: require(classes/Page.php) [function.require]: failed to open stream: No such file or directory in /home/folder_name/public_html/51/includes/utilities.inc.php on line 4

    Fatal error: require() [function.require]: Failed opening required 'classes/Page.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/folder_name/public_html/51/includes/utilities.inc.php on line 4

     

    It seems like for some reason the Page class is not loaded.  It's probably something simple and obvious, but I don't see it. 

     

    Any suggestions?

     

    The utilities file code is straight from the book and php version is 5.3.29:

    :

    <?php #utilities.inc.php - Script 9.3
    //Define a function that will autoload the classes:
    function class_loader($class){
    	require('classes/'.$class.'.php');
    	}
    	spl_autoload_register('class_loader');
    //Start the session
    session_start();
    //Check for a user in the session.
    $user = (isset($_SESSION['user'])) ? $_SESSION['user'] : null;
    //Create the database connection as a PDO object.
    try {
    	$pdo = new PDO('mysql:dbname=xxx;host=localhost','xxx','xxx');
    	//Catch any PDO exceptions.
    	} catch (PDOException $e){
    		$pageTitle = 'Error';
    			include('includes/header.inc.php');
    			include('views/error.html');
    			include('includes/footer.inc.php');
    			exit();
    			}
    
  13. On the Chp 9, CMS site I can't figure out why I'm getting a warning and a fatal error on utilities.inc.php line 4 when I try to add a new page.  Is there a setting in php.ini that needs to be changed or something else that I'm obviously missing? 

     

    ( ! ) Warning: require(classes/HTML.php): failed to open stream: No such file or directory in C:\wamp\www\ullman_advanced\chp9\includes\utilities.inc.php on line 4

     

    ( ! ) Fatal error: require(): Failed opening required 'classes/HTML.php' (include_path='.;C:\php\pear;/wamp/bin/php/php5.5.12/pear/') in C:\wamp\www\ullman_advanced\chp9\includes\utilities.inc.php on line 4

     

     

    The code for my utilities.inc.php and add_page.php are added below. 

    Any assistance will be appreciated.

     

    Here is the code for my utilities.inc.php file:

    <?php #utilities.inc.php - Script 9.3, see page 294 for explanation.
    //Define a function that will autoload the classes:
    function class_loader($class){
    	require('classes/' . $class . '.php');
    	}
    	spl_autoload_register('class_loader');
    
    	
    //Start the session
    session_start();
    //Check for a user in the session.
    $user = (isset($_SESSION['user'])) ? $_SESSION['user'] : null;
    //Create the database connection as a PDO object.
    try {
    	$pdo = new PDO('mysql:dbname=cms;host=localhost','root','');
    	//Catch any PDO exceptions.
    	} catch (PDOException $e){
    		$pageTitle = 'Error';
    			include('includes/header.inc.php');
    			include('views/error.html');
    			include('includes/footer.inc.php');
    			exit();
    			}
    

    Here is the code for my add_page.php:

    <?php #Script 9.15, 
    //This page both displays and handles the "add a page" form.
    require('includes/utilities.inc.php');
    //Redirect if the user doesn't have permission.
    if(!$user->canCreatePage()){
    	header("location:index.php");
    	exit();
    }
    //Create a new form:
    set_include_path(get_include_path() . PATH_SEPARATOR . '/wamp/bin/php/php5.5.12/pear/');
    require('HTML/QuickForm2.php');
    
    
    $form = new HTML/QuickForm2('addPageForm');
    //Add the title field:
    $title = $form->addElement('text','title');
    $title->setLabel('Page Title');
    $title->addFilter('strip_tags');
    $title->addRule('required','Please enter a page title.');
    //Add the content field.
    $content = $form->addElement('textarea','content');
    $content->setLabel('Page Content');
    $content->addFilter('trim');
    $content->addRule('required','Please enter the page content.');
    //Add the submit button.
    $submit = $form->addElement('submit', 'submit', array('value'=>'Add This Page'));
    
    //CHECK FOR FORM SUBMISSION AND VALIDATE.
    if($_SERVER['REQUEST_METHOD']== 'POST'){
    	if($form->validate()){
    	//insert the record into db.
    	$q = 'INSERT INTO pages (creatorId, title, content, dateAdded) VALUES (:creatorId, :title, :content, NOW()';
    	$stmt = $pdo->prepare($q);
    	$r = $stmt->execute(array(':creatorId' => $user->getId(), ':title' => $title->getValue(), ':content' => $content->getValue()));
    
    	//If the insert query worked, freeze the form to show the results.
    	if($r){
    		$form->toggleFrozen(true);
    		$form->removechild($submit);
    		}
    	}
    }//End of form submission.
    
    //Create the page.
    $pageTitle = 'Add a Page';
    include('includes/header.inc.php');
    include('views/add_page.html');
    include('includes/footer.inc.php');
    ?>
    
  14. For Chapter 9, After lots of searching I found a great tutorial on how to install Pear on WAMP Server, the prerequisite to QuickForms2.   It's detailed and step by step with screenshots. 

    http://www.steptoinstall.com/install-pear-wamp-server-windows-7-8.html

     

    Once pear is installed with success it was just a matter of using using the cmd line and typing pear install HTML_Quickform2.

    I changed the set_include_path in login.php to:

    set_include_path(get_include_path() . PATH_SEPARATOR . '/wamp/bin/php/php5.5.12/pear/');
    require('HTML/QuickForm2.php');
    

    Works perfectly.

     

  15. I was able to finally solve uploading both images to the directory.

     

    I'm trying to insert the information to the table and I'm receiving the following error message:

     

    An error occurred in script 'add_image.php' on line 195: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, boolean given
    
    My connection to the database works because I have a select statement in my form to create a drop down list of my clients.

     

    I also made sure that the number of '?' marks equal the number of columns in my table. Also, I made sure that I have the same number of bind parameters for each variable.

     

    I'm not sure what else I can do to troubleshoot this.

     

    Can someone lend me a hand? Thank you in advance. Here is the INSERT code.

    $q = 'INSERT INTO photo (client_id, photo_name, description, image_original, image_thumb) VALUES (?, ?, ?, ?, ?,)';
    		$stmt = mysqli_prepare($dbc, $q);
    Line 195:	mysqli_stmt_bind_param($stmt, 'issss', $c, $pn, $d, $oi, $ti);
    		mysqli_stmt_execute($stmt);
    

    Looks like a comma too many in the VALUES after the last  question mark.

  16. I'm adapting the e-commerce knowledge is power tutorial into another script.  I have a table of employees and PDF certifications, working perfectly.  I can't go live until I have a way to delete pdfs and the Effortless e-commerce book doesn't really cover this, at least not that I can see. 

     

    I see there are other tutorials out on the web, but I want to try this forum first.  I know I need to use unlink, but I don't really have a clue how to begin.  My plan was to use the delete_user.php (script 10.2) that was in the PHP and MySQL  for Dynamic Web Sites Fourth Edition as a starting point.  This script only deletes a record from the database and does not use unlink.  I'm assuming that I need to delete the record from the pdfs table on the database and then unlink to remove the pdf file from the directory.  Could someone please point me in the right direction?

  17.  

    On a brighter note, I've complete everything else on knowledge is power, including the paypal side. If you have time, check it out at www.wolfcut.co.uk I'd really like to say thank you again for all your help..... onto Coffee Shop next :)

     

    Armlocker, I was reading through your post and thought it was cool that you put your website link to a live example from the book, however I was a little bit let down when it linked to a Joomla site...What happened?  Did you give up on hand coding?  I used Joomla for years, the first install was always great.  But I found out that It took so much effort to maintain a Joomla site, sometimes I couldn't sleep at night thinking about it.  Especially when doing sites for other people.  I had finally just had enough.  Once I discovered Ullman's books, I've never looked back.  

  18. Here is the working code, using one query:

    <label>Type:</label>
    <select name="ruh_type_id">';
    $q = "SELECT t.ruh_type_id, r.ruh_id, t.type_name FROM ruh_type AS t LEFT JOIN ruh AS r ON t.ruh_type_id = r.ruh_type_id AND r.ruh_id=$id";  //$id = r.ruh_id
    $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].'"'; 
    			if ($menu_row [1]== $id ) echo 'selected'; else echo '';
    			echo '>'.$menu_row[2].'</option>';
    			}
    		}
    mysqli_free_result($r);
    echo '</select>';
    
  19. Hi HartleySan,

    It is working now with the two queries, confirmed.   

     

    Margaux,

    I did use the CONCAT as you advised.  That part looks like this:

    CONCAT_WS(' ', first_name, last_name)
    

    Because I am using MYSQLI_NUM:

    while ($menu_row = mysqli_fetch_array($r, MYSQLI_NUM)
    

    I dropped the alias "name".  This is also working.

     

    Since all the code is working, for now, I will move forward with the project, however it's definitely an issue I will try to improve later.  If I do figure out a way to make the dropdown work with one query, I will post the answer.  

     

    Of course if the answer just happens to magically appear as a post somewhere on the forums, I'll take that too.  Hint, Hint  :)

     

    Thanks for the help.

×
×
  • Create New...