Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Moving the navigation to a function

From: PHP with MySQL Essential Training

Video: Moving the navigation to a function

Throughout this chapter we've been making improvements to our navigation. And our navigation code has grown as we've added more features to it. By now it's become a pretty large block of code on our PHP page. To me, this is a signal that it might be time to do another round of refactoring. Now there's two ways that we could go with this refactor. First, we could move all of our navigation to a separate PHP page. Maybe something called navigation.php. And then we could use include to include that PHP page in whatever page we wanted to have our navigation displayed in.

Moving the navigation to a function

Throughout this chapter we've been making improvements to our navigation. And our navigation code has grown as we've added more features to it. By now it's become a pretty large block of code on our PHP page. To me, this is a signal that it might be time to do another round of refactoring. Now there's two ways that we could go with this refactor. First, we could move all of our navigation to a separate PHP page. Maybe something called navigation.php. And then we could use include to include that PHP page in whatever page we wanted to have our navigation displayed in.

Or, the other choice is, we could move all of our navigation to a function, and then when we call that function it would generate the HTML that we need for the navigation. Either one of these approaches would work. It's really just a matter of which coding style you prefer. Would you rather work in HTML most of the time with some PHP sprinkled in, or would you rather work in PHP most of the time with some HTML sprinkled in? And I think that the first one, using an include page, I think you can probably just do that on your own. It's pretty easy, just cut and paste that over to another page and use an include statement.

I'm going to show us how to do it by using a function. Because I think we can learn a little bit more by doing it that way. So, the page that has our navigation now is managecontent.php. We're going to open that up and I'm also going to go ahead and open functions.php because that's where were going to put our navigation function. And TextMate lets me just fold up all of these just by clicking right here on the side bar, and then I can make a new function which will be called navigation. Makes sense right this is where I'm going to put all of my navigation code. So, let's find the navigation over here. What I'm going to do is grab everything from this ul the top all the way down to the ul at the bottom.

That's what I'm going to cut, so I'm just going to cut that out now my navigation is just this div that's left. And I'm going to come over here and the first thing I'm going to do is I'm just going to paste this in, right in the middle. Now that's not going to work because I'm inside PHP here, this is all PHP code, and I just dropped in some HTML. So, I've gotta turn all of this HTML into strings in PHP, because I made the choice to work mostly in PHP with some HTML sprinkled in. So, the way that we're going to do that is we're going to just put double quotes around all of our strings, and then we're going to put output as a string. Then we're going to build up with all of the HTML in it. So, output is going to start out being equal to this. I have double quotes inside double quotes, so I need to escape those with a backslash, that tells it that this is just a double quote inside the string not an ending double quote.

So, I've done it now to the first one and even now I'll go through the rest of them. And I need to strip out the PHP, I have a PHP tag I don't need to turn that on because I am in PHP right? So, that will get a little bit cleaner same here. And then every time I have an echo statement instead what I need to have is output and then append equals. And that's going to then add that to the string that I've already started up here. Every time that I was echoing something before, from PHP, now I'm going to build it up in this output string. Now we could just do echo from the function, but I think that's a bad idea. I think it's better to have functions return something, and then we have the option to echo it once we work with it there.

Now, some people disagree, some people like to have functions that go ahead and just output from the function. But I think it's a better idea to build up this string instead. So, let's go through, and every time we see an echo, let's just go down the list we're just going to drop in our new output equals. We're not even going to really worry about the code yet. We're just going to indiscriminately go through all those echo statements. Okay. And we got them all. So now, let's come back and do a little more cleanup. So I've got my loop started. I've got an output. Then I've got my conditional statement here. That's all PHP, so that's okay. Now I don't need my PHP tag anymore.

Now I've got another bit of HTML so once again I need to figure out where the HTML part is. That's right here put double quotes around it and then put my output at the beginning. Once again I've got a double quote inside a double quote so I need to escape that. Lets make sure we have a semicolon at the end. And were just going to repeat this process all the way down the page. Just building up the string in this variable called output. So, urlencode, that's fine. We don't need our PHP tag here. Now these two characters our HTML. Don't be confused by that.

I also have a double quote in there that needs escaping. And then,we've got more PHP. See how this works? Do you follow the process? Once again, I've got some more HTML here. So, we're going to just do output equals and then we're back to PHP. Page set equals, and then we've got some more HTML one more time. Same thing put it in double quotes. Escape any double quotes that are inside of it. And then output append equals to the front of it. Okay now we've got our pages actually I'll put a little break here just so that's clear that's where the pages start.

And again I don't need my PHP tags let's just bring all of this back over a bit. That's all just PHP so its already okay and good to go. Here though I've got some more HTML. And let's come to here, and it goes all the way to there. Put double quotes around it, and the semicolon at the end. Escape, the double quote that's inside of it. And output, append equals in front of it. So, once again, building up another line in my string. So, then we'll remove that. Once again, these two characters, don't be confused.

Those are HTML. That's the ending that I need. Dollar sign, output and go, once again, a little more HTML here. I actually can bring that up and put it in the same HTML block, that's fine. Output, and, and I don't need the PHP tag, but I do need this closing to my loop, and then, I can free up the result. Alright, and I've got a little more HTML here. I'm going to put quotes around the whole thing, semicolon at the end. Do check and make sure that you've got semicolons at the end of all these lines.

It's real easy when we're doing lots of changes like this, to lose track of those. And then we've got MySQL free result, just indent these correctly. Subject set, don't need that anymore. And my last bit of HTML. Okay, so hopefully you followed along. You can go back and double check yourself you want to make sure you have semicolons at the end of all the lines. Make sure that any time that you have a double quote inside a double quote that you've escaped it. Make sure that you're always using append equals, to add things to output. So, now we should have something that will assemble a string and assign all the parts to it to output.

The last step is that we need to return that as the result of our function. The very last step is return output. Okay, so that's good, we've got that but we do need to make another change here which is our navigation needs a little more information. It needs to know what the currently selected subject idea is. That's right here. So, we need to look at that. All of these parts are part of the loop. But selected subject id and selected page id are variables that are in our global scope. So, we could call global on them and bring them in. However, I think that it's actually better in this case not to do that.

But to take these and put them up there as arguments to our navigation function. I'm actually not going to call it selective subject_id I'm just going to call it subject_id and page_id. And that will be the name of the local variable we will use inside our function. I will do that for both of those. So, now I just need to pass in those two values and it will be able to do the rest. That's all that it needs to know. It needs to know, what is the currently selected subject, if any? What is the currently selected page if any? Let's make a code note here. Navigation takes two arguments.

The currently selected subject id, if any and the second one, the currently selected page id, if any. Okay, so that'll tell me what I need to be passing in. So now I just need to call it. So let's take this and copy it. Come back over here and inside our navigation, we'll open up some PHP tags. And we'll echo, make sure you echo, our navigation and we're going to pass it in selected_subject_id and selected_page_id. Those two values are going to be passed in, so selected_subject_id becomes subject_id as a local variable once it gets inside the navigation.

Don't let that throw you. Alright, so let's save both of those, and let's try it out. Let's go to Firefox and let's see if we have any bugs in our code. Nope, it reloaded for me just fine. Now, if there's no change, everything is the same, but that's exactly what we wanted. We refactored it. Remember, refactoring the result should be that we have the exact same behavior, we just have better code behind it. Is this better code? I think it is, because now we have this one function called navigation which takes care of our navigation for us and look at our page now. Look how much cleaner this is. We have our code here at the top that loads everything, that figures out what subject and page we're on. But when we actually get down to the main content, that's it. Just one line.

Navigation. What are we doing here? Well, we're echoing the navigation. It's very clear and concise. It makes the code more manageable, more maintainable, easier to understand, and more flexible. And those are our goals when we're doing a refactor. So, we've done a lot of work on our navigation here, but I think we've finally got something that really works well for us as this navigation. And we're able to select content and now the next step is for us to start working with those selection over here on the right side, in that manage content area. What we need there is the ability to create, read, update, and delete our subjects and our pages.

And we'll learn how to do that in the next chapter.

Show transcript

This video is part of

Image for PHP with MySQL Essential Training
PHP with MySQL Essential Training

131 video lessons · 34214 viewers

Kevin Skoglund
Author

 
Expand all | Collapse all
  1. 4m 8s
    1. Welcome
      1m 0s
    2. Using the exercise files
      3m 8s
  2. 15m 6s
    1. What is PHP?
      3m 52s
    2. The history of PHP
      2m 51s
    3. Why choose PHP?
      4m 10s
    4. Installation overview
      4m 13s
  3. 54m 53s
    1. Overview
      2m 33s
    2. Working with Apache Web Server
      6m 56s
    3. Changing the document root
      7m 24s
    4. Enabling PHP
      6m 16s
    5. Upgrading PHP
      3m 30s
    6. Configuring PHP
      10m 3s
    7. Installing MySQL
      5m 46s
    8. Configuring MySQL
      7m 24s
    9. Text editor
      5m 1s
  4. 31m 25s
    1. Overview
      3m 27s
    2. Installing WampServer
      5m 46s
    3. Finding the document root
      2m 24s
    4. Configuring PHP
      8m 12s
    5. Configuring MySQL
      5m 45s
    6. Text editor
      5m 51s
  5. 19m 12s
    1. Embedding PHP code on a page
      6m 43s
    2. Outputting dynamic text
      5m 55s
    3. The operational trail
      2m 27s
    4. Inserting code comments
      4m 7s
  6. 1h 18m
    1. Variables
      7m 50s
    2. Strings
      4m 38s
    3. String functions
      8m 54s
    4. Numbers part one: Integers
      6m 27s
    5. Numbers part two: Floating points
      5m 25s
    6. Arrays
      10m 0s
    7. Associative arrays
      6m 37s
    8. Array functions
      6m 33s
    9. Booleans
      3m 50s
    10. NULL and empty
      5m 15s
    11. Type juggling and casting
      8m 27s
    12. Constants
      4m 43s
  7. 27m 37s
    1. If statements
      6m 0s
    2. Else and elseif statements
      4m 16s
    3. Logical operators
      7m 30s
    4. Switch statements
      9m 51s
  8. 42m 15s
    1. While loops
      8m 41s
    2. For loops
      5m 59s
    3. Foreach loops
      8m 16s
    4. Continue
      8m 28s
    5. Break
      4m 8s
    6. Understanding array pointers
      6m 43s
  9. 37m 25s
    1. Defining functions
      8m 25s
    2. Function arguments
      5m 32s
    3. Returning values from a function
      7m 33s
    4. Multiple return values
      4m 53s
    5. Scope and global variables
      6m 2s
    6. Setting default argument values
      5m 0s
  10. 20m 18s
    1. Common problems
      3m 47s
    2. Warnings and errors
      8m 36s
    3. Debugging and troubleshooting
      7m 55s
  11. 57m 57s
    1. Links and URLs
      5m 33s
    2. Using GET values
      5m 35s
    3. Encoding GET values
      8m 41s
    4. Encoding for HTML
      9m 26s
    5. Including and requiring files
      7m 40s
    6. Modifying headers
      6m 45s
    7. Page redirection
      6m 43s
    8. Output buffering
      7m 34s
  12. 1h 3m
    1. Building forms
      7m 28s
    2. Detecting form submissions
      5m 59s
    3. Single-page form processing
      7m 57s
    4. Validating form values
      10m 40s
    5. Problems with validation logic
      9m 54s
    6. Displaying validation errors
      7m 23s
    7. Custom validation functions
      6m 28s
    8. Single-page form with validations
      7m 25s
  13. 28m 5s
    1. Working with cookies
      2m 49s
    2. Setting cookie values
      5m 55s
    3. Reading cookie values
      6m 1s
    4. Unsetting cookie values
      4m 51s
    5. Working with sessions
      8m 29s
  14. 48m 39s
    1. MySQL introduction
      6m 43s
    2. Creating a database
      7m 41s
    3. Creating a database table
      7m 42s
    4. CRUD in MySQL
      5m 48s
    5. Populating a MySQL database
      7m 32s
    6. Relational database tables
      6m 40s
    7. Populating the relational table
      6m 33s
  15. 56m 4s
    1. Database APIs in PHP
      4m 51s
    2. Connecting to MySQL with PHP
      7m 45s
    3. Retrieving data from MySQL
      8m 47s
    4. Working with retrieved data
      6m 12s
    5. Creating records with PHP
      6m 58s
    6. Updating and deleting records with PHP
      9m 6s
    7. SQL injection
      3m 5s
    8. Escaping strings for MySQL
      6m 45s
    9. Introducing prepared statements
      2m 35s
  16. 35m 58s
    1. Blueprinting the application
      7m 19s
    2. Building the CMS database
      5m 14s
    3. Establishing your work area
      4m 38s
    4. Creating and styling the first page
      4m 22s
    5. Making page assets reusable
      6m 36s
    6. Connecting the application to the database
      7m 49s
  17. 32m 49s
    1. Adding pages to the navigation subjects
      5m 58s
    2. Refactoring the navigation
      6m 7s
    3. Selecting pages from the navigation
      6m 2s
    4. Highlighting the current page
      5m 26s
    5. Moving the navigation to a function
      9m 16s
  18. 1h 45m
    1. Finding a subject in the database
      9m 48s
    2. Refactoring the page selection
      10m 52s
    3. Creating a new subject form
      6m 55s
    4. Processing form values and adding subjects
      11m 20s
    5. Passing data in the session
      9m 16s
    6. Validating form values
      9m 40s
    7. Creating an edit subject form
      8m 30s
    8. Using single-page submission
      7m 44s
    9. Deleting a subject
      9m 44s
    10. Cleaning up
      10m 37s
    11. Assignment: Pages CRUD
      4m 30s
    12. Assignment results: Pages CRUD
      6m 10s
  19. 39m 26s
    1. The public appearance
      8m 52s
    2. Using a context for conditional code
      11m 37s
    3. Adding a default subject behavior
      6m 9s
    4. The public content area
      5m 51s
    5. Protecting page visibility
      6m 57s
  20. 1h 3m
    1. User authentication overview
      4m 3s
    2. Admin CRUD
      8m 41s
    3. Encrypting passwords
      7m 26s
    4. Salting passwords
      5m 42s
    5. Adding password encryption to CMS
      11m 54s
    6. New PHP password functions
      3m 13s
    7. Creating a login system
      11m 28s
    8. Checking for authorization
      5m 48s
    9. Creating a logout page
      5m 40s
  21. 2m 4s
    1. Next steps
      2m 4s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed PHP with MySQL Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.