How to Submit an HTML Form to a MySQL Database Using PHP | John Morris | Skillshare

Playback Speed


  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x

How to Submit an HTML Form to a MySQL Database Using PHP

teacher avatar John Morris, I help freelancers get clients.

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

7 Lessons (2h 13m)
    • 1. Forms ARE the Internet

      4:29
    • 2. How to Build a Simple Form

      34:48
    • 3. How to Secure Your Form

      33:26
    • 4. How to Build an Advanced Form

      27:08
    • 5. Cleaning Up Your Form With a Functions File

      17:13
    • 6. How to Display Your Data

      14:21
    • 7. Next Steps

      1:16
  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.

1,566

Students

3

Projects

About This Class

Forms are the internet. Look at any popular application or website... Facebook, Twitter, Google, WordPress, YouTube. You use a form to submit a Facebook post, a tweet, a search, post a blog or upload a video. Knowing how to submit data from a form into a database opens you up to be able to create all kinds of amazing things.

Take Wufoo Forms, for example.

It's a simple online service that helps non-techies to build online forms. It was started in 2006 with just $118,000 in angel investments. By 2011, it sold to SurveyMonkey for $35 million. And, as of 2014, SurveyMonkey, itself, is valued at $2 billion.

So, this is a huge industry.

Learning this one thing could be all you need.

Now, nearly a decade ago, I created PHP forms tutorial. And, for those 10 years, it has remained my most popular tutorial, by far... with 781,458 views on YouTube. But, it's nearly a decade old. So, no HTML5, no CSS3, no PHP7. That's why I created this course.

That's why I created this course.

To bring that tutorial up to date.

Show you the latest in HTML5 and ensure its compatibility with CSS3 and PHP7. To teach you the concept of "Layered Defense" and how secure your online forms against hackeres, spammers and anyone with bad intentions.

So, whether you're looking to create the "next big thing"...

Or, just need simple contact form.

This course will teach you the skill that's responsible for all of it.

It's six lesson, just over 2 hours of runtime and includes the full source code for you to download, follow and use as you see fit.

Enroll today to get started.

Meet Your Teacher

Teacher Profile Image

John Morris

I help freelancers get clients.

Teacher

Click here to start this class

See full profile

Class Ratings

Expectations Met?
    Exceeded!
  • 0%
  • Yes
  • 0%
  • Somewhat
  • 0%
  • Not really
  • 0%
Reviews Archive

In October 2018, we updated our review system to improve the way we collect feedback. Below are the reviews written before that update.

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.

Transcripts

1. Forms ARE the Internet: Hey there, John Morris. Here, John Morris online dot com. This lesson. I just want to kind of give you a primer in why I think this skill set is so important and why I think that just learning this one thing alone can I mean it can really free you upto do some amazing things when it comes to Web designed and Web development. Now I know that people kind of roll their eyes at that, but But I want to do is just kind of show you some of the different things. So, for example, let's take a site like Facebook. I what? The main thing that you do on here is post statuses and replied to statuses, It could be on your own timeline. It could be on other people's stuff. It could be in groups at the end of the day. What you're doing is you're posting data into a box. This here is a form so ultimately, the core around what a site like this is built around is forms. If you head over to Twitter again, the main thing you do here posting into a form when you were a reply to other people's posts your posting into a form when you upload a video to YouTube. I would drag a video over here, and then I'd have a whole form that I would have to fill out. If you want to go on imply for jobs. This is all a form that I need to fill out here. Even Google, the search engine, is a form that you have to filled out. So point is that form building and understanding this basic fundamental you take all the stuff that people like to talk about at all the fancy stuff Ajax and we want to do note. And we want to do all of these things. At the end of the day, the very fundamental thing that you have to do that runs all of this stuff is forms. You're filling out forms, and so being able to do this kind of thing is just that. It's that fundamental skill that will allow you to then be able to do kind of whatever you want. Now, obviously, there's a lot more complex complexity that a lot of this stuff I mean, Google has all sorts of algorithms behind it. Facebook, etcetera. But at the end of the day, the interaction that that they have with the end user is through a form. So knowing how to do this is a very foundational, fundamental, critical skill that when you learn it, you can kind of do with it what you want. You can kind of go all sorts of different ways and again, like I said, it opens you up to be able to build some amazing things on the Internet. So I want to teach that foundational skills going to teach you how to do it with HTML, my sequel and PHP and I want to kind of I want to make sure I'm clear that it's not any one of those over the other. So, for example, in the course, I'm gonna teach you some of the new stuff and html five that you can use for some basic validation required fields, using email fields and all those sorts of things that will allow you to to harness the power of H home, teach two mile five and what's new in that to help you with your form. So there's there's definitely a strong focus on the HTML part of it, but we're also gonna go into the my sequel part of it, and talk about, you know, building your database and the different data types and how toe actually show you how to create. Ah, your your first database. If you haven't done that in all those sorts of things, we're gonna get into that. And then, of course, there's the PHP code in between that connects the two, and we're gonna go heavy into that. Talk to you about security securing your forms, um, doing with built in PHP stuff primarily, but also showing you some options you have. If you want to step outside of that, you some third party stuff validation sanitization preventing SQL injection, preventing cross site scripting attacks. All those sorts of things were going to get into inside of this course. So if you want to learn this foundational skill ah, you want to learn how toe take data from a form, put it doing to a database and then be ableto to retrieve that data back out of the database and do it in a very concise, specific, precise way than I'd encourage you to dive into this course on tackle head on. So that's a little about the course of a little about what we're going to get into, so that said, Let's dive into it. 2. How to Build a Simple Form: Hey there, John Morrissey, John Morse online dot com. This lesson we're going to this is kind of a simple form tutorial. Now there's still a little bit that goes on here, but what I want to show you here is the base connection from your HTML form to your PHP processing script and ultimately into your my sequel database. How those 33 things all connect up. So that's what we're gonna be going through here real quick. Before you get into that, I just want toe get a couple things kind of out of the way so that we don't get bogged down with those. So over here, first off our structure I have three files. I have conflict got PHP, which we'll get to in a minute. Have simple dot PHP, which is the one you're looking at now, has most of the code, the form and the processing script in all that. Then I have this style that CSS so style dot CSS is pretty, just basic CSS. I'm not going to go through all of this because I want to really focus on the PHP parts of this, but it's what kind of gives this It's a little bit of the look here, so I didn't want it to be a just a completely kind of plain form. But it's just some very, very basic styling here, all right? And so Ah, you know, like I said, I'm gonna pretty much not cover that anymore after this point. All right? So, uh, the first thing that I really want to go through here is I want to kind I want to cover the form real quick, and then I want to hop into the database and show you how to create the database that we're gonna submit this into. And then that'll give us kind of where we're starting with the form where we're ending with the database. And then we can talk mainly about the code between the two. Okay, So if we come down to the form Ah, just ignore this all up here for a second. Starting here with this doc type declaration, I have a standard kind of HTML page that you would have here with an HTML tag ahead tag, body tag. I'm setting the character set. This is for mobile responsiveness here. Um, I'm linking in my style sheet right here. I have my title tag here. So this head area, nothing really special about this. This is all pretty much standard H two most stuff. You see, I have this kind of book PHP block here. We'll get to that in a second. I don't want to go into that yet because it doesn't really make sense until we get into the code part of this. So the big thing that I want to focus on right now is this form part. So this is the actual form that we see over here on the right. So when we write our form tag, there's a couple things that we need to specify at a minimum. So we need to specify the action. And the action is essentially where we want to send the data that's gonna be submitted by the form. So in this case, we we've left it blank. And what that means is that this form data that gets submitted is actually gonna be be submitted right back to this same page. So this is what would be a called a self submitting form. And that's why our PHP code that processes it is right here on the same page. Now, if you wanted, you could put something like, say, process dot PHP here. And then you could come over here and you could create a new file called process dot PHP. And you could take all of this code and put it over there if you wanted. Um one. I wanted to keep all of the code kind of in one place, so we were bouncing around between a ton of files. Be a lot of times. A self submitting form like this is perfectly fine for what you need, So Ah, I just decided to do it like this. There's not any necessarily Ah, you know, there's not necessarily a right way to do it, but that that's just what I've decided to do here. Next is the method, and it's set to post. Now there's there. The the two main options that you can put here are either post or get, and you may or may not be familiar with those. Essentially, the difference is if you submit data via get So if we were to change us to get like this, what that would do is when this for Miss submitted all of that data would be appended to the U. R L as query parameters, and that's where you would actually pull the data from so with and most of the time, the only time you really do that with kind of standard forms is with a search form and that the reason you do that with the search form is because if you want a link to certain searches than all you need to do is have, the quicker you can run the search, grab the query parameter. You can actually link directly to that search without having to submit the form to do the search. When we have a form like this where we're ending, you know, a name and email, it's kind of sensitive data. Generally, we don't want to put that in the URL. So most of the forms that you're gonna have are going to use this post method. I would say me default to using post unless you know for sure have some compelling reason why you need that data. Ah, in the URL appear after that, I've got kind of some standard html here of some wrapping each one of these fields in Ah Div. With a class of form field, that's just kind of help style a little bit. You certainly don't even have to do that if you want. It's not necessary. Super important. Here you can see each one of the inputs and then the button are all inside one of these Ah , form field dibs. The main thing here is these input types. So we're doing an input tag. We're setting the 1st 1 to a type of text because that's our name. And so we just want text string text there. Ah, we're saving the class to text. So that was so we could target with our CSS. Then. The big thing here is we're setting that the name of this input to name. Okay, So Ah, you might you could that were too confusing. You do full name. You could do first name whatever you want the name of this to be when you're gonna process it in code. That's what you would say here. Ah, the placeholder. Here's that's what puts this end of your name thing in here. So, um, that's what the placeholder does. That's kind of a new sort of html five type thing And then we have this tag here called required, which means HTML will see the browser will see this field as required. And so if we actually try to submit this form without any data, will say, Please fill out this field. So it's an easy way to have some really basic input validation there. But again, the big thing for our code purposes is the name of this is set to name, and we have another input field. The type is set to email. So what? By setting the type Tomo, what this is going to do is it's actually going to provide us a little bit of validation. So if we try to do J. J J. And we don't have any at sign here, all right, and we try to submit this form, it's going to say Please include that site in the email address, and so it's going again. Do some basic email validation now. It's not foolproof. For example, you could do J J. J at BBB, and it would let me submit this form. Okay, so again, it's just real basic. But, you know, we kind of use everything that's available to us again. here. We kind of have this set to class of text again. We have the placeholder here, but the name of this one is now email. Okay, so and then we have our button down here. I've said a button with a class type of button so we could target instances pretty straight for it. Okay, so that's the form, The main things again, Like I said or this name are the name elements here. These air What? We're going to show up on our code, and I'll show you where? Here. Ah, in just a second. Okay. So actually, let me just go ahead and do that here. So I'm gonna do print are. And I want to show you how this data is submitted, print or in post, and then we're gonna exit. Right after that, we're gonna is gonna print what's in this post block, and then we're gonna kill the script so that we can see what's in there. So I'm gonna type in my name and Justin email address here. I'm hit. Submit slips. Anita, put print are, uh all right. Well, reload that. And so what? This does. So I want to try and make sure this is clear. If you're not familiar with this, whenever you create a form like this, this a Peter and HTML form like this and you put the method of post what that actually is going to do when you submit the form. When you submit the button for the form is it's going to take the data that was in each one of these input fields, and it's going to put it into what's called a super global. And a super global is essentially, um, it's a variable that in PHP that's available everywhere, right? So it's it's a global and it's a super global, so it's just it's available. Basically, everywhere you don't have toe, there's nothing you have to do. It's just kind of magically there, Okay? And ah, so that's what when I do this print are that's what this is. Okay, now, if you had used the get method and study using post like that, you would use print are get okay, and there's other super global's that are out there. But those are the two when you're working with formed out of your primarily gonna work with , and so all of our data that submitted in the form. No matter how many inputs we had, we could add 100 more inputs in here. All of them are going to end up in this post super global. And that super global is, as you can see here, an array. And it's got our name and our email from our form. Okay, so that's why this name part right here is important, because that's what's going to be the key in for each element in our array. If we change this to full name, this would now be full name in here. Okay, So these air how we're going to reference what was submitted in the form throughout the rest of our code case. That's important, too toe to keep in mind as we go through this. Okay, so now I'm not gonna go into all of this code yet because I want to go to the other side and only show the database site because ultimately, that's where data is going to go. So for me, I'm gonna go over to PHP my admin now, depending on what environment you're in, maybe on a hope local host like Wamp server or, um Ah, Zamfir. Something else like that they usually have PHP my admin available with that? Ah, lot of times you just go to if you're accessing it out. Local host, you would go to a local host slash PHP, my admin. So that's actually for me. That's what I do. I just I have Ah, you are l for mine because it's a cloud I d. And I go to PHP my admin and and this is what I get for your on ah kind of a regular Web server, Then you may need to go in to see panel and see panel. There's usually you can kind of scroll down and you'll find a link there that says, PHP my admin. It'll kind of let you go into your different databases and you'll see something similar to this. It all depends on what version of that they have installed and all that sort of thing, so may not look exactly like this, but it should be pretty someone. It'll be close enough that we can kind of function here on us on a similar page, So I don't have the database created all yet, so I'm gonna actually show you how to create the database. So the that's kind of the first thing that we're gonna wanna want to do here, ah, is to create a database. So what we're going to do here is you can see I'm on the home here. I have all these options over here terms a query window, all these sorts of things. If we wanted, we could click into one of our databases here. Um, looks like I got logged out. Do Teoh activity. Someone log back in and and again. So there's there's all sorts of options in here. The thing we're looking for here is this Databases links will click on this and you'll see right at the top. We have this create database, so I'm gonna create a database called Forms. Okay. And if you know the collation here, you have something specific that you want to use. You can certainly do that. Um, I think as of this, I hesitate to tell you something specific, because this kind of tends to change a decent amount. So you'd need probably out of look this up at depending on what time you're viewing this tutorial. I think the recommended right now is utf a and before underscore been so we'll just go ahead and use that here. We may just want to do a quick Google search for kind of standard database collation and see what seems to be the flavor of the day for that particular time period. But anyway, or you could just leave it blank and let it it kind of pick its own. But we'll hit, create here. And so now it has created that database and you could see that database is over here, so we'll go ahead and click on that. And now what we need to do is we need to create a table that we're going to submit this data into. So we're gonna create a table called users and the number of columns we're gonna set to three. And I'll show you why here in just a second. So users Columns three and will hit Go. Okay, so we know we have our name and our email of the data that we're going to submit into this database. So that's only two columns. Why do we need three? What? We're gonna create what's called an I. D column. So we're gonna give this 1st 1 a name of I D, and I'm gonna leave that set to ent. Um, I'm gonna set this to 20 and ah, we're going to go primary key and not no, no default value. And that should be good there. So what we're doing here Oh, way. Need to set auto increment. That's crucial here. Okay, this AI is auto Inker may need to make sure that that's checked. So basically, what this is going to do is every time this for Miss submitted, it's going to create a new record in our database and we'll take a look at what that looks like here in a second. But we want to be ableto numerically kind of index those right? If you think of an Excel spreadsheet when you're in the spreadsheet, you have numbers along the left side. That's a 1234 and you have numbers across across the top that say a B C D. Well, by default, a database like this doesn't have those numbers along that left hand side. So if you want those and you pretty much any application, you're gonna want those you need to you need to actually create that. And so that's what this I D field is now. When you put on this ah, auto increment, what it means is you don't have to manually put the numbers in there right, so you don't have to specify the one, the two, the three. What it's going to do is when the first record is submitted, it's gonna automatically give that the number one the next record is gonna automatically give it the number two. So that's what the auto increments means. It's going to auto increments. As each record eyes added, It's also going to use this as a prime, the primary key. So it's basically telling, Ah, my sequel, that this is the primary key for this database that we're gonna be using for four King. Essentially adding these I d numbers is what that is. So for King, this table. Ah, and it needs to be unique and all that sort of thing. So that's what this column is. Next, then, is the ones that you would kind of standard think of. So we're gonna have name and we're going to now you could go back and forth here if you're gonna have something that has, you know, maybe this is a comment box. Or maybe you're creating a CMS and you're gonna put Ah, this is gonna be your post content box. You would do something maybe bigger, like text. Or maybe you could go down here to a long text, depending on how much data you think is gonna be put in there. You kind of decide. And there's all sorts of information out there about how to decide that. How what? One's air, right? For what scenario? Ah, again, I want to try and keep this simple, So I want to get in on that. But here, we're going to use var char, and we're just gonna go 20 because name is going to be, you know, it's gonna be fairly. Most names are gonna be fairly short, so we don't have toe toe. Actually, we're going to 40 because that should be plenty for what we need here. And then we're gonna go with email and we're gonna go with 2 55 which is kind of a standard thing for ah, using emails we're gonna do var char again. So far, charge just means it's a variable. Characters that could have, you know, five characters in it, it could have 20 just is something that's that's a variable. And the way that it feels kind of affects the way that it fills the data into the database . So you're not taking up as much room helps with performance a little bit. That's kind of the basic idea here. It's not something to get too wrapped up into for these. I would just kind of stick to to this here and then We don't need to set anything else for any of these so we can go ahead and hit save here and now that's going to create those. If we go to structure, we now have our I. D field. We have our name feel and we have our email field. So we now have our structure that we can submit our data into. So we have our form that has the that's gonna actually collect the data we now have our storage space that we're gonna store that data into kind of are are. If you want to use the analogy of a spreadsheet, we have the spreadsheet. We're going to store the data into now. We need to connect to the two together. So when the form is submitted, it actually submits it to this table and this this database. So that's what the PHP code we're gonna talk about actually does. And we need to sink those things up. So would that said. There's a couple things that we need to look at here. So the first thing is, we need to go into our conflict file. I like to put this stuff in a conflict file, and we need to. We need to specify a few things here for accessing our database, so the first thing that we need to specify is the name of the database. So remember, we created the database. It's called forms, and so we're going to specify that the name of that database. Next, we need the user. So in this case, I'm just using the root account because I'm in a I'm in a testing environment, and so the user name in the passwords or user and pass here. It's rude, and it's a blank password. Now that's default on, I would say, if using something like William Server example. It's been a while since I've you Some of those. But my recollection is that's pretty standard for testing environments That's gonna be route and then a blank password. You may just need to check with whatever one you're using. It maybe a little bit different. So you just check and then see, um, But when it comes to actual production servers, most of the time you're gonna have a wizard where you actually create the database through see panel. And when you create the database is gonna have you set a user name and password, and so you're gonna have those. Just make sure you kind of copy those down somewhere. So you have those available to you, but those air what you would put in here for the host most set up such is gonna be local host. I have seen some, I think, Go, Daddy, where you have to specify something a little bit different. So if you try local host and you're getting some sort of air that about that related to the host, then you may go to your documentation for your Web server and see if there's something else you need to specify or contact your support there to see if there's something else you need to specify here. But I would say most of them, it's gonna be this local host thing. All right, so we're putting all of this in this conflict file, so we don't have to constantly redefine it. We're defining them as Constance, which means they're kind of basic. The way to put it is their kind globally available. They're gonna be available inside and outside of functions by default. We don't have any functions in the simple version, but ah, in case we did, it's just kind of standard practice to put these in the conflict file. Right? So I'm gonna go and close this because we won't be using it anymore. You can see we're doing a require once here to require that conflict file into our simple dot PHP file says that's basically bringing in the data from the conflict file. So now that we can Accel assess those constants here, All right, so that's set up. You can see here. This is actually our insertion code right here. So you can see it's really pretty simple. There's not a ton to it. So the first thing we're gonna do is we're going to see if this post super global has any data in it. And the reason that we want to do that is because if we go to this form and no data has been submitted, So when someone first lands on the form, we don't want to do anything because there's no data to work with. And so we just are checking to see if this post super global is empty. If it's not empty. So that's what this exclamation point before empty means. So not empty. Then that's we're gonna when we're going to do the rest of this stuff here. Okay, so we'll get rid of this here for a second, and we'll save that. And so the first thing that we're gonna do we need do is make a connection to my sequel. So we're gonna instance eight a new instance of my sq life. So this is kind of the built in my school I extension for ah, for PHP. And of course, you could use PDO here. If you're familiar with that, you can certainly do that. And you can swap that out here. And I'm just going trying to go with kind of the standard What? What's here and available? Um, inside a PHP, although again, PDO is these days. But in any case, we're gonna stand she a new instance of my school. I this is gonna open up a connection to our database or to my sequel and then select our database for us to be able to start working with. So we pass in the database host, which, remember, was local host. We passed on our user name, which I remember from our conflict. Profile was route. Our password was blank. And then the name of our database, which was forms and what this does is creates basically a connection to our database that we can now start running queries on. Okay, Now, we need to do that first, because I'm gonna use this method that's available to my SQL. I called real escape string. Um, and you need to have the connection of my sequel before you can do this. OK, so that's why we need to do this first. So what we're gonna do is we're gonna run a rain map. So essentially, what a ray map does is it's going, it goes through an array, and it said every element in that array to a callback function that you specify. So what we're passing in for an array is our post array. Remember, we had our array that has all of the information from our form in it. So we're pat. That's the array that we're gonna loop through. And the the function that we're going to send it to is actually a classmethod. And and so when you do a classmethod instead of just putting in the function name here Ah, you put in a ray and you pass in the object. Ah, variable. Here. So my sequel, this is what we connected to and we passing, then the the method main. So essentially what this array map is going to do is gonna take every element in our post super global post array, and it's gonna run it through this, my sequel, Real Escape String Method. Now, what that method does is essentially escapes the data. So this is just a basic sort of security thing that we're doing here, and then it takes that escape. It takes that escape data puts it back into array, and it gets saved as this data variable and you'll see from here on this data, variables gonna be kind of what we work with. So this is a really, really basic security check here. Now, I want to caution you here. This is the absolute bare minimum. And really, the only reason I even did this is because I didn't want to give you code that didn't have at least the bare minimum in terms of security. But this is not sufficient security for really using this in production. Okay, I'm gonna talk about security in the very next lesson. We're gonna go in and go kind of all in on how to secure this, but I kind of debated between Ah, putting this in. They're not putting this in there. And I decided to put in there because I just didn't want to give you something that didn't have at least ah, bare minimum. But this is not sufficient. I'm trying to focus on the connection to my sequel and all that sort of thing. So I'm trying not to go heavy, heavy insecurity here. So what I want to caution you is thinking Oh, well, I'm good on security. I'm secure now. Yes, it's gonna escape the data and it will probably be fine. But there are some caveats to that, and there are some Ah, we're not doing everything exactly perfectly here, so Ah, I just want to make sure that that's clear. All right. So that out of the way, then the next thing we're gonna do is we're gonna run extract on our data. So essentially, what that does is extract takes the elements from our array and it turns them into variables. And so it takes and it uses because it's an associative array. Let me just go ahead and print this Ah, array back out. Since we're talking so much about it, so and then exit. Let's go ahead and submit this form again so we can kind of see the data that we're working with here. So Smit that Okay, so we have an associative ray means named key value pairs. So this is the key, and then this is the value for this element, and that's the first element in the array. And then we have a key and a value for this element here. So what extract does is essentially takes this data and it creates a variable called name whose value is set to John Morris. So this would be essentially the same thing as saying Name equals John Morris. All right. It creates a variable with the name of the key and the value set to whatever's in the value here. Okay, so we're just doing that because we have an array. We're just doing it without having to specify each and every element Ah, that we want to work with here. Okay, So, essentially, after we run extract, what we have is we have a variable called name and a variable called email, and they're set to this data from this array. Um ah. Uh, accordingly. So now we can actually use that data. We need to do that because of the way that we're passing in the data here. Um, we using using the Data street from the array wouldn't work route were very well. This is gonna be less of the thing when we get into the next part where we talk about securing it. But now here we can set up our query. So for inserting data into a database, we use the insert into the name of our table, which remember, was users and then the columns that we won t submit the data into. So remember, in our database we have a column. We have the I. D. Column. The name column in the email column. Now we don't have to. Like I said, we don't have to specify the i. D. It's gonna auto increments, so we can't even submit data to it, even if we wanted. So all we need to specify are the other two columns. So the name column in the email. Calm. So these the calm we're going to submit data into. And then these air the values. And so it's name and email variable. So that's the data that we got from our form. So we go from the form to our post ah array from our post array into our query here. So that's how we're tying our form through our PHP cold, ultimately to our database. So we're matching up columns with data from our form. That's this is ultimately this variable name is data submitted from our form. This variable email is data submitted from our form, so it's passed from one thing to the other. Okay, and these are in order, so if I were to switch this around and say email name, the PHP code doesn't know any different. It would submit the name the name variable into the email column. Okay, so it's It's dumb in that sense. So you need to make sure that these air in the same order as one another, So name, Name, email, name, email. Right. So now, once we have that query all set up, then and let me just run this were Meteo prints are on because I could just echo it. But we'll just do this since we're already there. Print are there. Let's get rid of this one and show you the actual query hopes. Need to resubmit the data. And so you can see insert into a user's table the name and email columns, the values John Morris and the female sports remorse online dot com. You also noticed these ah, single quotes here. Those need to be there as well. Okay, just the way that it works. You need to have those there. Otherwise the create won't work. All right, So once we have all that, then all we need to do is run our query. So we're gonna pass our query that we just created here into this my sequel, query method, which is actually going to run the query, send it to my sequel and get a response back. So this is the actual everything up to this point, really? It's setting up to run our query. This is where we actually run it. Is this line 14 right here? Okay, so when we do that, essentially with now, the query method, depending on it, depends on what sort of query statement you send. So if you send a select statement, you're actually grabbing data from the database. And so you're gonna if the query goes through, you're gonna get that data back. And there's certain other ones where what this query method returns is gonna be different. But with an insert statement like this, this is simply going to return true or false. Okay, so this insert variable is either going to be true or it's gonna be false. Ah, and so then we can use that. That's then what we use down here to specify our message. All right, so, again, at this point, our data is either submitted or it's not, and then down here, we're going to say, Well, OK, if insert is set to something, right, so if it's set to anything, then we want to see what it set too. So if it's, ah, we're gonna display this either a success message and air messages depends what it set to We need to wrap this in is set. Otherwise the rest of these will give you a notice error. So basically, run is set first and then inside of that, if it's set to true, we're gonna run this success message and if it's set to anything else other than true, which would be false because it's either true or false that we're going to display an air message and that there was an air with this submission. So if I I'm gonna just reload this, you can see we got this. Data was inserted successfully Message from that data we just submitted. If we come over to our database here, we click back up on our users. You can see now we have our I d field. We have our name column, our email column, and we have our data submitted into or form here. So it was successfully submitted so again, that is the pathway from the form through the PHP code ultimately into the database. So that is how to submit data from an H tomo melt html form into a my sequel database using PHP. Now, I know I probably thrown a lot at you there. What I would recommend is you get in here and kind of mess with this yourself. We can talk about more fields and so forth. Um ah, a little bit later. But get in here and mess of this yourself setting up your database. You know, uh, kind of figuring out the code, Go through this again if you need to, um and just kind of really kind of dive into this because this sort of thing, this form to database sort of thing is just it's a really just key fundamental of building any sort of application or really building a website that has any sort of interactivity to It doesn't matter. For your collecting names and emails, it could be anything if you look at Twitter, twitter tweets or it's a form that you're submitting to Facebook posts. Ah, there's a form you're submitting to. If you upload a YouTube video. Most of what you have to fill out is filling out a form, so everything is forms. So this is a really key fundamental skill for if you want to be a coder just website building. In general, if you wanna have an interactive website, you want to collect information. It's a key skill. So dig into this kind of go through it, get your head around it, and it should start to become a little bit more clear. All right, that will do it for this lesson. Thanks for watching. We'll talk to you next time. 3. How to Secure Your Form: Heather John Morris here, John Morris online dot com This system. We're gonna talk about how to secure our form now. So there's a few things that we gotta adhere and just to kind of cover just really briefly the mindset here, The thing I always try toe to tell people about when it comes to security is thing is to keep in mind is there's no kind of hard, fast rules because ultimately what you're dealing with is you're dealing with people who are trying to hack stuff. So every solution or thing that we figure out in order to help make something more secure, they're always trying to find ways around those toe hack in different ways and so forth. So that's why securities kind of always this evolving kind of revolving door on different things that we gotta learn. But with that said, there are some fundamentals that we can go through some basics that we can do in order to ah, secure the known threats that are out there and kind of building a way where it would be difficult to hack or Garlits of the approach that someone might take. So there's a few things that you want to keep in mind with this. Their first off, there's kind of what I would call form of validation, and that's probably a little bit different than what you've heard. The way you've heard that talked about before on I'll make the distinction here but for invalidation is actually validating that the data we received to our post script. So the part of our script that's gonna process the post Atta the form does received one was actually from was actually our form, because when you have a script out there that will process post data, it'll process that post data from an Ajax request. It'll process it from ah, curl request filed, get caught any of those sort of things so someone could actually find your form and find out where your processing script is. In this case, it's on the same pages or form, and if they wanted to, they could build ah program or use a programmer script that would send out a to it not actually from this particular form. So what we want to do is kind of help eliminate all of that, and there's a way that we can do that using not, ah, form nuances and we'll talk about that in this video. There's also what I would call input validation, which is mawr. What you think of when you think of form validation and that is the actual data that submitted in each of the inputs validating and or sanitizing that data before we're gonna put it into our database, Then we have preventing ah SQL injection attacks, which we're gonna talk about that and using prepared statements and then another one that we would have would be cross site scripting attacks. And we're not gonna talk about that in this video because you deal with that when you actually go to display the data which we haven't got to yet. But when we talk about displaying the data, all also cover those cross site scripting attacks. So all of that said, Ah, those were some of the things that we're gonna talk about how to defend against those and some fundamentals that you can go through to do that. So a little bit of set up here. First off, if we go to our conflict file, you will notice that I've created a new constant here called nonce soul and I have kind of a random a string of characters in here. Now you can It's ah, random dot or guy believe it is. You can help use that to get a random string of characters. Now, this sort of thing. What I'm gonna show you with all the hashing stuff that's not recommended for passwords PHP has built in password hashing stuff. So, um, this isn't this is just for generating and nonce. Um, and it's not ads, because even if someone gets around, this we're still protecting gets SQL Injection attacks will show you a way that you can another way they can deal with spam and so forth. So it's not as mission critical. I would say so. Ah, you know, we don't We're gonna kind of standard hashing algorithms here, But if you're dealing with passwords and a store those in the database, it's It's pretty critical that you use the built in PHP stuff, but again, you can goto random dot org's and it allow you to generate random strings I recommend. Basically, what I do is a generate five stern five strings that air 20 characters and then all grab two or three of them and combine them together to create this nonsense. Every say that you, uh, installed this form on O R. Really, every page that you're using this form on should have a different not salt. If you use the same, not salt across different forms becomes easier for someone to figure out what that nonsense and actually be ableto hackett. So you should always be using a different non salt for every instance of this form. Ah, that you're using. And then we'll go into some other ways that we're gonna make this variable as well. But I've got this definition of this non side. This is something not salt. This is something you'll have to add manually again. You can use random dot or to help you generate that stream. All right, so once we have that, then there's a couple things that we've added to our form. So if you come down here, we You see, we now have three hidden input fields here and those air time action and hash it. So are the names were time stamped form, action and form hash. So, basically, the the idea here is whenever this page loads essentially What we're going to do is create create what's called a nonce, which is a number used once. And every time this page loads that nonce is going to be different because it's based off of the time. So if, uh, look, if we come back up here, you can see we're setting were grabbing the time now. So this is a time function is a built in PHP function that gives us UNIX timestamp case. We're going to set that for setting this action to submit form. So the way the action works is basically whatever you're trying, any time, any sort of action that you're taking that you want to nonce right, that you want to do this sort of protection for should have a Each one of those should have its own action statement. So, for example, if we were in a CMS and we wanted to let someone click a link to delete users, we could knots. We gets nonce. Ah, that doing Ah, using a form and using get as opposed to post. But that delete action that would be one action in and of itself. So delete post would be in action. Another action inside that TMS might be to delete a comment. Delete comment would be a different action or delete a user delete user would be a different action or delete category would be a different action. So they're all different actions, and they would have different values here for this action. So you would actually change this right here for each one of those. Now with this again, just like the not should be different for every instance of this form that you put on your site. This action should be different as well, so I just did submit form to keep a generic. But whatever this for Miss four. So, for example, let's say this is you're kind of generic. Opt in form so you might put generic opt in. And then if you put this in another part of your site and you've changed the input fields completely and you're taking your feedback so that would be the feedback form so you would use a different action. So it's important that these variables air different for the different instances of this form where you're using, whether it's different sites or different pages on the same site. Ah, it's important that they're different Because if you keep them the same across all these forms, if someone really wants to try and hack your site, they're going to start to be able to figure out, ah, the nonsense and and so forth and the it makes it easier for them to be able to hack your site. So you want to make all of this stuff different. So we've got the time. We've got the action and we've got are not sold. These are the three things that we're gonna use to create a hash. So you could say I'm using Sprint F here. The way Sprint F works is these percentage esses or placeholders. So the action gets put in place of this. Ah, this one here, time gets put in place of the 2nd 1 and the non salt gets put in place of this 3rd 1 So, basically, what we have is we have action underscore time underscore are not salt. So that's our string. We've just created a string out of those three things. And then what we're going to do is we're gonna run them through this hash function using this Shah 5 12 algorithm. Um and passing in this string, and we're going to save that toe hash here. So this is what creates our hash. Okay, so if we listens, reload this page or quick if I inspect this And remember, we're echoing that hash down here in this hidden field called form hash. Okay, so if I inspect this down here, this is essentially what we're getting. We're getting this long string of characters okay that we created according to a pattern. Now, what's important is that we've created that that hash, But we got to submit this form, and when this form submit is gonna reload this page, and so all this time value is going to get reset toe when that page reload. So it's actually gonna be different than what it was when we submitted. Ah, the form. And so we have to actually put the time stamp in our hidden field here so that we can weaken re We can check our hash. That was passed based off of the time the form page actually loaded, not when it was submitted, because that will basically make it so they don't match. Okay, so that's why we're putting time stamping here and form action in here because we're gonna actually submit, Remember, we're using, Ah, time we're using action, and then we're using a nonce. Well, we're putting in the time the action and the hash that was created when when this was all loaded. So we have everything we need to make our comparison and then are nonsense stored in our conflict file. So the thing the hacker doesn't know is the the knots. Right? So they could come to this and they could see over there using time stamped using this form action. Um, but they don't know the nonce. And so that's kind of like if you think of a public key and a private key, that's how a lot of AP eyes and stuff work. Now, the nonsense essentially kind of our private key. And in a way, so again, what this allows us to do is it's our forms, basically not going to submit if our nonce doesn't match. Okay, so we're setting up a way for us to know that it was actually submitted from this form in particular. All right, so once we have all that set up, then what we can do is we go back into our remember we had before. If Post, if Post is not empty, then we're gonna do stuff with our post data. Now all of this in here has changed. I'll just tell you that now, But I'm gonna walk through this all step by step. So the first thing I do here is just extract Post. We're not going to use a ray map and my my sequel, Real Escape String of that anymore. We're gonna use prepared statements and do it right. And so we just need one thes in variables. It's gonna be easier to work with. So Extract is going to take all of our post data and create variables out of it that we can then work with. So the very first thing that we're gonna then do is check our knots. So what we're gonna do is we're gonna remember up here we created stream like this. Well, what we're gonna do is we're going to recreate that string now with the but we're going to use this submitted data. Okay, So we're gonna take remember, form action was the action that was submitted in this field, and we're going to the time stamp is the time stamp that was submitted in this field. So now we're taking the stuff. That was the, um, data that was submitted by the form. And we are creating a hash out of. We're creating essentially a new hash out of that. Okay, so and then on. And that's what these two lines do right here. They basically are the same as these two lines up here, but they're the data that was submitted by the form. Okay, in the form Hidden fields down here. And then we're comparing that re calculation of the hash to the hash that was passed in the form. Okay, so we have a hash that was created when the page was loaded, and then we're recreating that hash when the for miss submitted, and we're checking against what we calculate when the form was submitted versus the hash that was created when the page loaded. And those two things have to be the same now. The only instance and with in which they would not be the same is if this the post data that was sent to our processing script didn't come from this form. Okay, so That's how we validate that This data, the data that was submitted to our post script came from this form. The only way for them to match is for it to have come from this form. So it eliminates basically people using Ajax and curl on all these other things to try and submit our form. It just a limit. Our form just won't submit. Okay, so that's what this all of that is intended to do. And that's what everything that's essentially creating all these hashes and then running this check right here. So on Lee, If they match, will we then go into the rest of this script? If there's not a match, were running this else block right here, which essentially sets insert toe false. Okay, so we're gonna get that. They would basically they're basically showing air message that says false. So nothing is gonna happen if that if that doesn't work so again, that's ah, kind of our first line of security is making sure that the data we got came from this specific form. All right, now, once we that's really the most complicated part of all of this, the rest of this is actually really, really simple, So Ah, and also, that's why when you're using hash, you're doing passwords I really recommend using PHP is built in functions because they're just functions you could call, and they make this a lot easier. The other thing is, is I couldn't make this. Ah, I could clean this up by putting this hashing algorithm right here the way we're hashing these into its own function. And then instead of having toe right recreated here, I could just call the function whenever I need it. But that creates an extra layer of abstraction that could be hard to follow in going from the form we had before to the form we have now. So I didn't want to do that. I wanted to make it a little bit, kind of verbose here so that you could see, you know, just I didn't want to make it 22 abstracted for you where it starts, you start to get lost a little bit. So again, we now have all of our nonce checking done. We know that the data that was submitted came from this form and again. This is not a mission critical there may be ways around this, but it's something that provides a kind of a base level of defense right off the bat. You know, it's not necessary. 100% foolproof and it but it doesn't need to be okay, just it's gonna kind of eliminate us from just 95% of the stuff and junk that might be out there. People trying to spam this or whatever. Uh, another option that you have here is you also have recapture. And so recapture is from Google, and they have version two. So if you've ever been on ah site and went to submit a form and they have that little check box that you have to check that says I'm not a robot that's recaptured, that's version two of Recapture. And so what you're looking at here, this is actually a peach P class that you can use to add in the recapture functionality. Now you have to go the recapture site and get a site key in a secret key and all that sort of stuff. But once you do that using this Ah, this this class is actually pretty simple. You can see a full example down here where you create a new instance, passing your site, keen your secret key. And then you're using this. There's a Java script kind of snippet that you have to add on the page, so that's what this does. Ah, and then there is a little line that you need to add in your form in your form field. So that's what this does. And then in your actual checking, you have a little check that you need to run, and that's what this does. So it's class makes it really, really easy to integrate. Recapture into your form. You could certainly do that again. I wanted to stick to built in PHP stuff. That's not third party sort of stuff because that stuff can always change. So ah, that's why we're doing what we're doing here with this stuff. But again, that recut capture thing is an option that will also help you do with spam and bots and so forth. All right, now, once we've done all that, now we can get into That's the foreign validation. Now we can get into the input, validation and sanitization. So So, first off, the difference between sanitization and validation sanitization is your allowing the data to go through, right? You're not going to stop the script, but you are escaping it or your sanitizing it in some way to make it safe. So you could be getting data that is dangerous. But you're running it through certain kind of algorithms in order to make it safe. So you're sanitizing it so and then validation is your checking to make sure it fits a certain set of criterion. If it doesn't, you're you're not doing it, you're not moving on. So which do you use and when It really depends on the data that's being submitted and different types of data. I would handle different ways. So things that are like mission critical that have to be have to be right. I would use validation, things that are you can, you know, would be great. If they were, they were right. But you can kind of go on even if they're not 100% perfect. Then I would use sanitization so you can see with our two variables here. We have good examples of that for the name were using sanitization because the name is nice toe have. But it's not necessarily. And again, this could change on content, depending on context. But it's not necessarily, ah, 100% mission critical. Where is the email address? We need the email address to be able to contact these people. So if they're submitting this form for us to be able to contact them, we absolutely have to have that in order for this to even be of any use. So we're gonna validate that. Another example is, you know, if you were if you had a text area on this form and are allowing people to submit feedback via that well again, the the email would be imperative. But that feedback wouldn't necessarily ah b that it has to fit a particular ah structure in order for it to be submitted. You can kind of, you know, if it's not 100% perfect is gonna be OK, so that might be more of a candidate for sanitization. So you have to think about that depending on the context of the application and the data that being submitted and so forth. But that's really the difference between the two. Now there's some several handy functions inside of PHP, but the one we're using here is called Filter Var. I've done some peers of videos in the past where he talked about filter input, which actually allows you to grab data straight from a poster array and filter it that way . But because we've already extracted everything up here cause we needed to in order to do all of our nonce checks and so forth now they're already invariable, so we can just use filter var. So and they really they do the same thing. So it's just a matter of the type of data you're dealing with. So we're gonna filter the variable name, and we're going to run it through Santa Tie the sanitize string filter. Now I recommend when you're looking to try and figure out what to sanitize and validate, just Google filter underscore var. And then on that page there will be a link that has a list, says some, like list of the different filters. Click on that and you'll see will save validation. Filters will say sanitation filters. A couple other ones that are there just kind of looked through those and see what fits the data and what you want to accomplish with that data in terms of validation and sanitization , because again, it's gonna be different for every scenario. But all that information is out there for you to look at. So this flag essentially tells filter var how it needs to filter this data. So we're gonna sanitize it and it's a string to string data. So that's what we're gonna and there's it's gonna if you go and look at these will tell you exactly what it does. And then for the email were again running through filter of our filtering the email, and we're gonna validate this and we're gonna validate that it's an email address. So this is actually going to validate that this is a proper email address and so I can show you an example here if we just go member before where I was saying, if you did at a at BB on this form html five won't catch that as an invalid email address. That's obviously an invalid email address. So if we submit this now, you can see we get the air message. There was an air with this submission. That's because of this validation check right here. So this is how you validate that these air proper email addresses. All right, so now we're storing those variables. Those filtered slash sanitized, validated variables as filter name and filter email. So we know these. There are now clean data, so to speak, or file data data. And then we're gonna run this check, so filter email when it's a validation, like when it's sanitization is just going to run it through the sanitizer and return the Saturn ties. The clean data eso it we've saved that. Is this filter name for validation. If it validates properly, it's going to return. The validated data here back is this variable. But if it doesn't validate properly, it's gonna return False. So basically what we're going to do is check filter email and if it does not equal false, so that means if it doesn't equal false, that means it is valid. Okay, coming a double negative hair. But if it does not equal false, then we know it's good clean data, and we can go ahead and then submit it to our database. If it's not clean data, then we're gonna run this else block here and again turn Ah said insert two false. And that's going to trigger air messages down here, right? And of course, if it's not, if it's is equal to false, none of this code in here is going to run, right, cause it in order for this code to run filter email has to not be equal toe false. All right, now, assuming that that's good data, then we're going to, ah, connect to my sequel again. This is the exact same before once dancing and new incidents of my s July or passing in our host or user are pass Ah, password and our database name. Here's where it gets a little different. Now, here's what we're gonna do is we're gonna use prepared statements so you can see instead of passing our query to my escalate query where we're passing it to my school, I prepare. Now. It's mostly the same in that we have insert into our table name. We have our columns, name and email. We have values, but in the values parentheses here we have to question marks. These are water called placeholders. So we're not putting the actual data into the query were saying, There's gonna be data here, but we we we haven't sent that data to you yet. And this is actually how prepared statements help secure. Ah, the queries that you send in my sequel. Because the first thing you do when you run this prepare statement What, you're actually sending this prepare statement to my sequel and telling my sequel? Hey, were about to run this query and we'll send you the data in a second. Okay, so you're splitting the query from the actual data that you're sending in the query and SQL injection attacks. Rely on those two things being together. It is actually injecting queary code in place of the data. When you separate those two things, it literally cannot happen. It creates a hard line between, ah, the query that's being run and the data. So when you do a prepared statement like this and we actually send our data than toe my sequel after we've sent them this this query, my sequel doesn't take the data and then put it into the query and run the query. It's already kind of got the query ready, and it just needs the data, and the two things never get mixed. Okay, so again, it's just a hard fix two SQL injection attacks. Which is why so many people say and recommend using prepared statements. There's just it's a hard line that can't really be crossed. So, uh, that's why we put these placeholders and we're not putting in the actual data, and then we're gonna tell it what data to use. And so that's what this next line is which is buying Paramus. So essentially what you're doing is you're binding these parameters to these placeholders. So you're telling my sequel. Okay, this is the data that we want to put in place of these placeholders. Now, you have these type identify IRS here thes are basically tell Tell my sequel what sort of data this is. In this case we have s for string. Could be imager could be flow to decimal. There's there's a number of them, depending on the data that you have, but in this case, both of these are strings. And so when you send the data, if you say it's an imager, but you send a string, it's obviously not gonna go through. If you say it's a string and you send an injured than it's obviously I'm gonna go through so This is just kind of one way of, ah adding extra security there and then again, because the two things air separate. We've sent the query through the prepared statement. Now we're binding the parameters to them, and then statement execute is where we actually execute the query and run the query. And this is going to this is kind of like before, um, you know, if certain certain sort of queries, they're gonna If there's a select querying expecting data back, this is going to give you a my sequel research source back that you can use to be able to get that data in this case with an insert because there's nothing we're asking for back. We're just going to get a tour false here. And so we're setting our insert equal to whether this is true or false. And if it's true, then we're gonna display inserts Gonna be set to true. That's going trigger our message down here for true, for some reason, it didn't get submitted, then is going to trigger false, and we're going to throw that message. So if we go over to our database here, we look at our users table here Let me go ahead and log back in. We look at our users table, you can see we have no doubt I have removed all the data from it. So if we just do kind of our standard thing and submit the you Zied says data was inserted successfully. And if we go back here, you can see that data is now in there If we go and again have kind of seen this. But let's just do this, uh, this sort of thing and we try to insert it. We're getting to air that it wasn't submitted, and we look over here, you could see it was not submitted. This is the data we had before. Ah, and then finally, if you would do something like this, we'll just do that email. So this is a quote and we're sanitizing member or sanitizing our string here. So there's different kind of flags that you can hear use here. Some will encode the quotes, and some won't in this case, this one will. It's gonna encode these quotes. So if I submit this, we're going to get the data was inserted because we didn't validate, we sanitized. But if we come over here on we look at our submission, you can see this was encoded. That quote was encoded into HTML entities, as opposed to staying as a quote. Okay, so that's that's a form of sanitization. And that comes into play when we start talking about, you know, if you're getting ah, sanitize String also is going to get rid of if someone tries to insert html code, but there's no reason to have a team Oh, code in the name block. Okay, so it's gonna going to sanitize out if someone sizes submit Java script, which is he is helping us deal with cross site scripting attacks on this side of it. You still want to do it on the display side, but it's we're dealing with it on this side as well. Okay, so, um, that's what that's why those quotes Aaron quoted encoded, because quote can be kind of problematic characters, depending on, you know, they're going to be used in if someone's trying to submit JavaScript. Oh, are there trying to submit SQL code etcetera. So encoding those helps make them not dangerous. So again, just different. Hopefully, the thing that you get from all of this is a specific, specific, practical things you can do. But really, it's just his mindset of layers of security. We have the form nods by itself, not necessary 100%. Ah, effective. But it creates a layer. Then we have filtering the variables where there sanitizing or validating again. There could be ways that someone could figure out to maybe get around that individually, but with the form dancing and then you had in this sanitation and validation and then you add in two prepared statements to prepare against issued injection attacks. Then you add in, we're going to do, um, help escaping for cross site scripting attacks on the display. So you just have multiple layers of security that becomes it becomes really difficult for someone to to try and hack what you're doing or find a way into what you're doing. And you know, this was something that I learned when I was in the military. But I said, this idea of being a hard target. Most hackers air looking for their for looking for targets of opportunity. They're looking for easy targets, so if they sit here and they start trying to mess with your stuff and they're running into the non stuff. And then the Senate ization it. They're just You know what? I'm gonna move on to someone else who is more vulnerable and make it easy, and that allows you to get passed over. And that's the whole idea of all of this. So hopefully that's the mindset you got from this again. Very specific practical things you can do. But probably the bigger, more important thing over the long term is the mindset of creating these different layers of security. And as new threats come out and emerge, you can learn about those, and you can learn how to add even more layers and ah, and so forth. So anyway, that's how to secure your forms. Those air kind of the base fundamentals on this side of it for doing that. So hopefully got something out of that. Thanks for watching. We'll talk to next day 4. How to Build an Advanced Form: Hey, there, John Morse. Here. John Morris, online dot com. This lesson. We're gonna get into a little bit more advanced form, and I'm gonna show you some of the other sort of input or field types that you can use in your forms and how to deal with those in your code. So, as you can see, here, we have over on the right hand side, we have, ah, some radio boxes. We have some checked boxes. We have a select box and we have a text area. So that pretty much is most of the stuff that you're going to use, probably on a regular basis for your forms. I mean, there's some other stuff out there, but they're not near is common. So I want to make sure and cover these. He's really common ones. All right, so if we go down to the bottom here, I can show you the HTML first, and then we can again go to our database and then go to our PHP code to connect the two. So we'll start off here with this freak frequency section here, and we're going to be doing our radio boxes. So first the input you said it to a type of radio, so that makes what makes it a radio button. I give it a class of a radios, like a targeted via CSS. Although I didn't actually add any CSS for the radio buttons here, Um, we'll skip the I d for a second, and then we had given a name of frequency. Ah, value of daily. And then you could see it has this checked, ah attributes here. Now, if we look at our other and I'll talk about that in a second, we look at our other radio button. You can see it has a input type of radio, a class of radio well skipped I d. For second use. You can see the name is the same, so its frequency as well, what's different is the value. This is how you handle check boxes because check boxes are meant to be an either or type thing. And so, ah, when the daily check boxes selected what's going to get submitted? Remember, our data that is in our form gets submitted to that post super global that post array. Well, when we have these two check boxes and they both have the same name, Whichever one does checked is the only one that's going to get submitted to our our PHP script. Okay, so we're not gonna have two elements in our ray. We're gonna have one, and it's either gonna be daily or it's going to be weekly. Okay, so that's how you handle radio buttons again? Because they're an either or situation. Um, and if you had three still radio buttons, Armento Onley have one of the three selected. So there's always only going to be one if you doing something different than that, you shouldn't be using radio buttons so that that's just something to keep in mind. When you're when you're building this. Now we'll talk about the i D. For a second here, you can see I have this I d set to frequency dash daily and frequently dash weekly and then on the label here I have four equals frequency dash daily and frequency Dash weekly for these. So this four attributes matches up to the air in the label here, matches up to the I d. Attribute in the input that is. So if I click the words weekly, it actually switches it and If I click daily, it switches it back. That's how you do that is using this four attributes, and it's to the I d of the input. So you have to add that I d if you want that that that sort of thing to work. Otherwise you have to click directly on the check box for it to work. All right, early of the radio button. I guess I should say next is check boxes. And so check boxes are a little bit different in that, unlike a radio button, that's kind of either or check boxes allow you to select multiple, so I can select all of these at once. So we handle these a little bit different. So for the input we have input type equals check box class equals check box. You already know why have this I d. Here. It's exact same reasons above. You can see my four label here so we won't really dig into that because the same is up here . So type check, box class check box and then our name. We have interests, and then we have PHP in brackets and here we have interests in HTML and brackets and here. We have interests in CSS and brackets and they're all set to a value of one. So, unlike check boxes where whichever one is checked is the one that's going to get submitted in this case, the ones it's still the ones that air checked. But because we're basically were there all interests and we wanna have essentially array an array of the interests that someone has checked. OK, so let me go ahead and we'll check those and let me just I want to show you this real quick . So we will come up here. We will print out our post array. Oops. Well, that guy's name and we'll exit there. And I was going through in some some data here and will submit this. That should give us what we need. Okay, so you can see that under interest right here. This is our interest element. It becomes an array and you can see it has an element of PHP set toe one in an HTML set toe one. So, basically, if we don't do this this way, if we set these all Teoh the name interests, we would only we wouldn't be able to have multiple inside of an array. Right? Because if it would work just like the radio button, it would only allow us toe have one that was selected. So what we're doing is essentially in our name block or using a ray notation by wrapping this in brackets. And that's Ah, that is what is ultimately creating this array right here. So we end up with this this ah, top level key name interests. And then we have an array in whatever boxes air checked. We're gonna have elements with those values Set toe one. Now, the one doesn't really matter in this sense, but, ah, we just have a value in there. So that it it is is set in here, okay. And then we'll talk about how to handle that. We're gonna kind of mess with that for Nagel that a little bit in our PHP code. But again, it's important that whatever check boxes you have that you use this sort of pattern right here. So you get this nice array that you can then work with. All right, so that is the check boxes. Let's go and reload this. The next is the country's. Now you see here actually have a list of all the countries in here. Um, I wanted to just kind of give you an example of a drop down, and I thought countries a pretty popular thing people want to know how to do. So I went ahead and did that. Now you'll see I have this country's file over here, so if we open that up, you can see it's just this list of countries. It's a big array with every country in it. Now, I didn't sit down and type all of these. Someone, fortunately, has done that for us. And I use this from get hub here. So, um, you obviously will be ableto to see and get the code that I have. But if you want to Ah, use this. You can just kind of Google PHP countries array. And this is like the first results come in here and just copy it. So that's exactly what what I did. I drop that all into a file here, and then if we go back here we go to the top. You can see I'm requiring that file in here. Just so I didn't want to drop that whole line just into this file here and kind of create a bunch of code in here that could cause a mess visually. So I just put it in its own separate found and required it in. So now that we have that array of countries, don't go ahead and close this, then what we can do is we can create our slick box from that. So we have select We have the name. I put a class of select and I'm I made it required course don't have to do that. But I did. And then we create an option with the value set to blank called. And then we, uh, set select a country here. And that's just so we have a nice select a country Ah, thing right here for us to use. Now, one thing to keep in mind with this is HTML five is smart. So we have this set to required, and technically, this select a country is an option. But if I try to submit this form like that, it recognizes that that value is empty and it's not gonna let me submit it so that that that's a handy little thing with HTML five. I have to actually pick a country here. Okay, so we just do this, this right here for for the visual look of this. So then once we have that, then what we're gonna do is we're gonna loop through our country's array and for each country, we're going to create a new option in our list here. So option. And the value is set to the name of the country. And then the this closes up the opening to option tag right here. This Ah, this sign right here. And then we eco the name of the country again so that it shows up. It shows up here. So if we inspect this real quick, you can see that we have option value equals, in this case, Afghanistan and then Afghanistan as well. So what you actually see on the screen is this in this case is what's going to be saved to the database now. You don't always have to do that. These values can be different from what you said here, if you have some sort of, you know, like I could make all the countries lower case that for some reason I wanted to do that. You know that might be a thing that that makes sense. So I could do that. But I just didn't in this case. So again we looped through, and that's what creates our actual list. Here is that array of countries and looping through that to create this. And then we close up our for each loop on close up our select tag, and that gives us our select box here. And then the final one is our comments section. So this is a text area. So it's text area classes equal to text area. Name is equal to comment, and we have our placeholder set to enter your comments here and then one thing about text areas that is different than some of these other ones, like the input fields, is they're not self closing. So you actually have a closing text area tag, and the reason that is is because you could actually write instead of using a placeholder, you could write default text and this would actually have default text in in here. The difference between the placeholders you see the placeholder, I can just start typing. Where is the default text? I have to I would actually have to copy that text and delete it out here would be actual text that's in the box. Anything you put between these two. So in this case, we're gonna leave a blank and just use the placeholder. Right? So that's the HTML may be familiar with that. Maybe not. Not entirely sure, but just kind of walk through it so you can conceive what it is. They're probably the most kind of nuanced thing. Is this thes check boxes here and doing this part right here? So just pay attention to that. Then let's go ahead and actually let me. Looks like I accidentally closed money. PHP. My admin slipped me kind of pop back over into that. You don't need this anymore. And so go to PHP. My admin and we'll go into our forms. Database will go into our users table. We'll go to structure and you'll see that I've created some more columns here. Now, how do you do that? You see right down here, when you're under structure, you see, it says add one columns and then at the end of table at the beginning of table. Or you can specify after a specific existing column. So I just had added four columns at the end of the table. So before we just had I d name and email. And then I added the four columns frequency, interest, country and comment. And so if I hit go here, it will bring up this to where I can do this. Now, I'm not actually going to I don't know if this will actually, Yeah. I didn't select any things that didn't actually add them, but that's what it looks like for these again. This is, you know who's probably debate about exactly how this is. You just kind of got a go with your I mean, God or what? You know, in terms of what type of structure to use here for the frequency they used tiny text because it is either gonna be weekly or daily. I know how maney word let letters or characters. It's going to be It's either going to be five or six characters, so I don't need to create a big, huge kind of block here for to be able to store this data. I know it's gonna be small and tiny Texas planning to hold it, so I just use tiny text here for interests. I mean, in this case, we only have a handful, but we are gonna be serializing it. We'll talk about that in a second, so makes a little bit longer. And then, you know, you could be adding any number of injured. I've seen forms that have, like, 30 or 40 no interest that someone can check. So it does. Kind of very so I I did go with Bar Char and I put 2 55 Um, that's probably bigger than what you ultimately gonna end up with. But I would just, you know, again, this could be used in multiple different ways. And this this interest block is something that could be, um, you know, it could be used. It could be a I have a number of different interests, so I just wanted to account for that country. Did bar chart to 55? I could probably cut that down because we know we can look at our list and see what the max number of characters in our list is, and so we can have a good idea of what we need here. Um, but you know, there's there's somebody long. There's some little bit longer names in the hair, and this is just kind of a standard like default thing for me. So I just kind of went with that. You could. You could mess with this a little bit. I just don't think it's too big of a deal for something like this. You know, we're not storing just millions upon millions of records and huge chunks of data, so I don't know how much of a difference it's gonna make. But if you do do really want to be conscious about performance, you could really tighten that up a little bit and then comment. I put to text. So I think that's probably fairly standard. Text is kind of. It's big enough to where you can take a decent chunk of text. But you know, you're not going to write like a full word. No 10,000 word WordPress blawg posts or something in. And I don't really want people submitting that in this comment block anyway, So tech seemed like a happy medium for me there, so those are the ones. I mean, that's all I said. I didn't set anything else for the rest of these. Um, but that's the database. That's where we're gonna be storing into again the column names or frequency interests, country and comment. We go to browse, then you can see that this is empty right now. So we come back over here, then what we're going to do is we're gonna just tie these new fields into from the form back into the database. Um, so a lot of this stuff at the top is the same. So I haven't change the hashing or any of that sort of stuff. The only thing I've really done is just added what we needed to add in these new fields. So you can see now instead, just filter name and filter email. I have these extra 33 here, which or frequency, country and comment. And we're using filter var and all of these air filter sanitized string because these are all ultimately strange. Now you might be saying Okay, well, the countries were pre populating that right? We're We're specifying what those are. Why do we need to sanitize those? Well again, it's possible for someone to potentially submit this form. Ah, in a way, not using this form essentially and so we just always have to assume that the data that we're working with is dirty in some way. So we always just assume, you know, you never assume clean data from any sort of user input. Even if you're specifying what what they can put into a particular form field, there's always waste for hackers to get around that. And you definitely don't want that to be your main line and defense. So we're still going to sanitize the stuff. So again the frequency is either daily or weekly. So that's a string of the country's air. All strings. The comment is a string, so I'm just using filter Santa Charlie stringing here. There may be some new wants that you could look into for the different fields again. You know, go to that filter input Ah ah, function and PHP and looked through the different filter. The link there's for the different types of filters. And see if something makes a little more sense for the data you happen to be collecting. But in this case, I just want to sanitize strain. Another thing I want to mention here is you know, you'll notice this is kind of verbose. I'm quite literally looking at every, uh I'm running everyone kind of manually, in a sense, through filter var There are ways out there for you to do this a little more programmatically and actually loop through the array and do it or you some of the array functions that are out there to do it. So you don't have to, um, right out each one again. As I mentioned before, I've decided in this tutorial to be a little bit more of her, both because I found when I start to get super concise with things, people that are new to coding 10 toe, that that tends to be a little bit confusing. And sometimes I think that that's like the only way to do things. And so I just I want to show you the really verbose way of doing it. And then as you gain experience, you'll I think you'll see ways that you can make this more concise. Now, just for those of you who are watching this, who kind of maybe a little bit further long and they're like, I really want to make that concise. What you would want is this function here filter import array. So if we come down here, you'll see it takes it takes a type, And in this case, we would be doing input Post. So it would be from our know, to use our post array. Ah, we can define some arguments, Will. Look at that second ad empty. I don't know. It's basically if Mr Key is missing, do you want to add knoll to that, um, may or may not apply to what you're doing, but you can see here this is simulating some post data. All right, so this is a post rate has product I d component, etcetera, here in our our eggs block, which is what we pass it in in our second parameter here to filter input array. So that is our definition parameter here. Um, what we're creating is an array, and we're specifying, for each key were saying use this filter. So if a product I d use this filter for the component key used these filters with flags and options for the versions. Use this filter so you could go through this and you could say OK for each one of these Elka elements in my array Ah, you specify what Ah, what filter you want to use and use filter input. Arrange said having doing it for both like this. But again, I just wanted to keep it kind of verbose, so you can kind of see how things progress along, but to make it more concise filter input arrays, what you're after now, the one kind of exception to all of that is the one called Array. There is the the field of the key called interests. And so again, I've extracted all of these up here. I guess I didn't actually mention that, but these have been extracted. So these are all now as, um, very variables. So the keys have been turned into variables. But with this one, because the actual value again that Ah, and we're getting the imager, right? If we remember our post array, we're getting the imager. Let me just print this back out real quick so that we can look at this because this is kind of important toe under stand. How this is coming together. All right, so let's just go ahead and check all of these. Let's submit that. So again, we have our interests key right here and it's an array. The thing that we actually need is the key, right, This one we don't need. We're gonna completely discard that because it's just there. So that this, because that's the way the form works is gonna show up here. But what we actually need the interest we need is PHP and HTML. That's what the data we want. And so that's what we need to sanitize here and again. We're just gonna completely dissed. Discard these these ones here. We don't need those. So what we do here is we actually do a for each loop on our interests array, but we run a ray keys on it first. So basically what that's going to do is it. When you run a ray keys on an array, it's going to take all the keys and creating new ray of just the keys. So that's actually what we're looping through here when we looped through here, this is an array of the keys, not this actual array right here when that basically right there just discards lease these ones and gives us an array of what we actually need. So for each array key as an interest, then we're going to create a new array called filter Interests. And we're going to run each one of those keys through filter of our because remember the thing, the attributes, What we actually need from our form is what ultimately came across in the key. So that's what we need to filter, because that's what we're gonna be storing in our database. So we're gonna filter each interesting. We're just gonna use filter, sanitize string, and they'll get saved back into this new array call filter interest. So again, just to show you what this looks like, we come down here and we do a print are on filter interests. After we've done all of this filtering, we reload this frame, you can see now what we have here is an array, and it has PHP each time. Ellen CSS It's an indexed array with our interests in it. And those those those ones that we had are completely gone. So this is what we're actually going to insert into our database, all right? From there, the rest of this is really, really pretty simple, pretty similar to what we've done before. So here we're checking to see if our email filters set to false again, just like we did before. We're connecting to our database just like we did before. But now we're changing our prepared statement. We're adding infrequency, interest, country and comment were adding in mawr placeholders to match up with those new fields that we're gonna be inserting data into, we've added four more type designations. They all happen to be strings again because we're gonna serialize our interests array here in just a second. And then we're passing in filter, name, filter, email, filter frequency. We'll talk about the serialized in the second, but filter interests filter country and filter comment. So basically, all we've done is we've just added to the code that we already had the extra columns, extra fields that we're gonna be submitting data into and match those up now serialize Here this PHP function. If you're not familiar with it, you can't take an array and just insert it into a database. OK, there's that. That sort of data type in my sequel doesn't exist. So if you want, there's a couple ways that you can handle this. You may have heard me talk about relationships, tables before. In some cases, that makes sense. In this particular case, I don't know that it necessarily does. So if you just want to kind of save it in a simple way, what you can do, it's serialize it. And essentially, what serializing does is it takes that array and it puts it into a string. But it's a string that's crafted in a particular way, so that when we pull the data from the database, we can use a function called un serialize and that will take it from a string back into an array so we can use it as an array. Okay, so serialized just makes it so we can stored in the database. And then when we go to display data, will unserious lies it and that will turn back into an array. Okay, so that's what serialized does here. That's why that ultimately, we have all strings here, and then we're gonna execute and clothes and all the stuff that we did before this is all the rest of this is pretty much the same. So now with all of my ex, it's gone. If I reload this frame, we should get data was inserted successful. If we come over here and we re look at this, you can see our data was put in their name email daily. This is what the serialize string looks like. Our countries Algeria. I must not left a comment. So let's just go back here and let's do weekly. Let's do html CSS us. And let's put in some comments here so you can see that we're getting the data that were supposed to have so weakly. Html CSS US comments Years will go ahead. Smith that and Korea to users. And you can see name email weekly now html CSS United States and comments here. Okay, so we're getting the data that we should be getting. And of course, if something failed, you would get the fail message just like you did before. So that's a that's a little bit more of an advanced kind of form and handling and so forth and showing you the different kind of the most common HTML fields form fields that you might work with and how to deal with them and handle those in PHP and store them in your database as well. Again, this is something on first kind of past. You're like, Oh, that's a lot. That's just fine. Get in and work with it. Get in with the source code and work with it. Um, maybe watch this video again. And as you're doing that and go through it and the more you start to just interact with it , the more it should start. Ah, to make sense. So that'll do it for this lesson. Thanks for watching. We'll talk to you next time. 5. Cleaning Up Your Form With a Functions File: Hey there. John Morrissey, John Morris online dot com. This lesson We're gonna kind of go through and clean everything up a little bit and kind of I've been hinting at the fact that there's kind of more concise ways to do this. And so I wanted to kind of go through that and show you that a little bit here in this lesson. So you can kind of take that next step with it. Now, looking at this page all kind of notice. Now, mostly, this page is just sort of html. There's a little bit in the header here now, but most of that code is gone, and we're actually referencing a couple functions. So create nonce in this process, method or function here and so down here instead of our If else blocks, we have do messages. So we've just kind of clean this up a little bit and I'm gonna show you just go through and show you what we did there a little bit now a couple things because we've taken all of what goes in post here, and we've put it inside of functions. The and the variables inside those functions are gonna be operating in a local local scope . Ah, we don't have to worry so much about collisions with these variables out here. So I renamed some of this stuff to probably be a little bit closer to what I would actually name it. So, for example, time stamp. Now instead of time form action is actually the same. And then we have nots instead of hash. And if we come down here kind of updated this in the form. So you see, this is time stamp and its echo. Timestamp here form actions the same. And then we have nots and eco nonce here. Okay, so just a couple changes on this front and hear of also like I mentioned have echoed to messages here, and we're passing in. Insert insert comes from here. We'll do some checks on that, that sort of thing. Um, but ah, that that basically takes most of the PHP actual code out of here and only brings it in via function call. So this keeps this a lot cleaner. So that's the whole idea here. Another thing is, when you notice here, have require once and then low dot PHP. If I open up low dot PHP. This has our conflict file our country's dot PHP And now it has this new file I created called function stop PHP and functions dot PHP relies on conflict dot PHP. So, um, I make major to call these in a particular order, but I'm a fan of these sorts of kind. These Ah, these load files like this because otherwise every page that you want to, you know, put this on, you would have to remember to require all of these things, Whereas if you put him in a load file like this, then you could just require that load file, and it's always the same. So, um, I like doing that to make things a little bit easier. So let's just run down through this. So I've got my require here, got my time stand, but got my for inaction. And then I'm passing that to a function called create knots, and I'm passing in the form action and the timestamp. So if we go over to this functions file here, you'll see I have a function called create nonce, and it takes the action and the timestamp, and it basically does what we did before it creates our string for us toe hash and then it actually hashes it, and then it just returns that So this is the exact same code we had before. We've just put it inside of a function so pretty straightforward. Ah, you also noticed that on all of these I wrapped them in. If function exists, that's just really kind of Ah, good habit to get into Just in case you have other things that are in the global space and PHP you could run into collisions. And so you run this if function exists here and you'll keep it from at least airing out at this point, and then you kind of know if there's, um you know, if something is not working here, then that will kind of give you a hint that something's going on there. So it's just kind of a good habit to get into, to check if a function that already exists before creating it. So that's why they do on every one of these. Then I have ah, this function called, uh, actually, Lett's go back to simple that PHP so create the nonce and we're using the nonce right here to put into our form. Um And so that's going What's gonna populate our form here? Ah, if we just look at this real quick are hidden field right here are nonsense value we create or not, so we can populate it there. So that's this function is creating that for us? And then you see, if the post is not empty, we're passing it to prop this process method. So if we go down to this process method, then this is all of the code that we had before for actually processing. Ah, the data. But we've kind of rearranged a little bit. Now, one of the things that is why I like ultimately putting this stuff and functions is because if you remember, before we had these kind of big, big blocks of if, if else so it was like this if else and then another. If else it was, they were, ah, kind of nested a little bit deep, and it kind of gets a little bit unwieldy and hard to deal with when you put something inside of a function. What's nice is you can actually check for false or check for a negative result as a result you don't want. And then if you get a result you don't want, you could just return. Okay, When you're not inside of a function, you can't really do that like that. And so this is why I like putting stuff and functions because it changes the way that we write our code and makes a little bit more efficient. So the first thing that I can do here now because of that is I can verify the knots because that's actually what I want to do first. I really don't want to do anything else unless I verified the knots. Ah, where is before we had we had to do some stuff in order to do that, and we had to wrap it in these this big l fells blocks. We can just check the nonce right off the bat. So we call this verify nonce function here, and we're passing in the nonce that we got from the HTML form. So again remember where we have nonce right here that's gonna be submitted as a part of our post data. So we're passing that that we're passing post into here and then using this variable. So that's our post nonce. That's what was submitted. Um, by our form are formed action from our post in the time stamps. So those hidden fields are all right here, and we don't need to do We don't need toe, you know, check anything in terms of security or that sort of stuff. Because we're not We're all we're doing is hashing them, and we're gonna rehash him and check the hash. So if someone's passing in some funky stuff, it just means the hashes I'm gonna work. So we passed this in to verify nonce. If we look at verify nonce up here, what it does is it takes the action in the time right here, and it uses create nonce to recreate the nonce based off what was submitted by the form to create our our re creator hash. And then it checks that against the one that was passed by the form. Okay, so we just exactly what we were doing before, we just now have it in functions. And so if that returns false than we are going to return false here, and none of the rest of this code will process because we've returned right here Okay, so that's what's nice is you can do like, you can kind of do a series of checks and just return false if you don't get what you want . And then once you've kind of done all these checks, you can then just run your code. You don't have to wrap everything in these big felts blocks. All right, The next one, so we've verified are not the next one we're gonna go into. We're gonna verifier validate our email because that's the next If our e mail is invalid, we don't want the We don't want the submission. So really, the same idea we're running our post. Our email that was submitted in our form through filter valid a email. If it's false, we're going to return false and just kind of kill the script at this point. All right, so once we've those are two kind of Maine checks that we're doing it at this point or to kind of validations after that. Now we can kind of check. We can kind of start to to normalize our data so that we can insert it into our database. So you remember I talked fairly? Uh, least a little bit before about how you can use filter, input array or, in this case, filter var array to filter through data from a variable or an input from like the post super global. To get super global etcetera, you don't have to write out each filter of our line. Well, this is an example of that. We can do that here. Ah, now in it. And it's a little bit simpler. So just like I said, you created our eggs array and for each one of the keys that from your post Ray that you want toe filter, you can put those in here. So Santa tight. Ah, name, frequency, country and comment. And we're gonna run those all through sanitize string. Now you notice we don't have email and we don't have interest. We don't have email because we already did email up here. We already did filter of our and we validated it. So this has already been filtered, so we don't need to worry about it. So we do. We're not doing that one here and also for filter interest, we have to do some special stuff with the interest. We kind of talked about that before, So we're not gonna worry about that up here as well. So we create this array and we tell our filter our function, what filters? We want to run for each key that we want to to to sanitize here. And then we pass that into filter of our race. We passed on our post data and we passed on our arts. And essentially, what is going to do is it's gonna match up what we specified here in our our eggs with what it finds in posts. Run it through that ah sanitization filter and then return the array as filter post. So this filter post right here is on Lee going to contain name, frequency, country and comment, and it's all going to have been sanitized. Okay, so it's just a little bit more efficient way of doing it. So at this point, we have filter email. We have filter name, frequency, country and comments. We have five of the six ah, that we need. Our last one we need is filter interest. And so, if you remember, we have toe we actually have to loop through our that Ah, that array. And we're gonna get rid of the ones that were in it, and we're gonna grab the keys and all that stuff that we did before. That's basically what we're doing here. One thing we're adding is this check. So if post interest isn't empty, because one thing that will happen is if you submit this form without any of these checked , you might have noticed this. If you submit this form and you don't check any of this, you would have got an error saying that this for each expected or actually is a ray keys expected this to be an array and and I think know what's given or something like that. So this deals with that. It says if this isn't empty, then we're gonna loop through it. Otherwise, if it is empty, we're just going to set it to a blank value, okay? And so and then it's just basically just gonna be blank in our database because we don't have anything set for it, which is what the fine for what we're doing here. But if it is, if there is data in it, then we're gonna loop through and do exactly what we did before. We're gonna get a rake, ease off of the interests. Um, And then we're gonna run those through filter var and create a new array of just the keys right here. And then here were actually serializing it here. The reason we're doing it here instead of down here. Now, you see, we're not serializing it in. Our buying cram anymore is because of this, because if we serialized it down here and it was blank, it kind of puts some wonky characters in the database, and we don't want that. We just want it to be blank. So we're serializing it up here now, and we're only serializing it if it's actually a Ray data. Otherwise, we're just gonna submitted blank right here, right from there. This stuff's pretty much the same. Ah, new instance of my school. I are prepared. Statement is exactly the same. Are buying cram. Our type identifies with the same. The only thing that's really different here is now we're going off of actually using our array filter post because, ah, if you try and extract off a filter post here just does it doesnt work. And so and it's not necessarily Ah, I'd say the best way to go about things in this instance. Um and so it and we there it's really only convenience that we would use it at this point anyway, So, um, before we were kind of we're doing it because we're using that data and different ways to run through filter bar. We could have still to use the actual array, but it was a little was a little bit more convenient. But here, um, you know, it's just doesn't work, and it's not really necessary. So we're just gonna use the actual filter post. Remember, that's from up here. After we ran it through a filter of our way for a name than our email, we did remember up here. So that's where this comes from. Filter, Post frequency filter Interest was another special one post country post comment. Okay, so that's that changes a little bit to pass that data in there, but that's just fine as well. And then we're going to run our execute statement and, uh, save the result of that which is either true or false as insert. We're gonna close our connections, and then we're gonna return inserts. So if you look at this insert or this This method, essentially this function could return false, false and then tour false here. So three false is and one true. It's only going to return true if the data goes and actually submits all the way through the the database, anything short of that, it's pretty much going to return. False. And remember, over on our simple that PHP were saving the result of process, which is this that's the function we're working with Over here is process. We're going to save the result of that as insert. So this insert is gonna be, ah either true. If everything submits or anything short of that, it's gonna be false. And then we're passing that into our do messages down here because we need to know what the result from the query was in order to do our messages. So we go back to do messages. This is basically what we have exact same thing we had before, except it's it's put into a function here. One of the maybe more nuanced things of this is we do have insert and it defaults toe knoll . So that's basically how this is right now. There's nothing in there's insert isn't even set, right, so it's not set or anything like that. And so if it's if the insert right here hasn't been run, we try and throw insert in here than it's basically that nothing's being passed in. And this is going to run this default, which is basically setting it to Knoll. And so the first thing we check to see is if it is no. If it's no, we're just gonna return because we don't There was nothing submitted. This is just the first view of the form, so there's there's no message to display. So, ah, if it's basically not know that it won't return, and then we can build our message and whether, if that's based off, whether it's true or it's false. So if it's true, we're going to play the success message false, we're going to display their message. So again, this is most, well, pretty much all this code. Really. I just copied over and put into functions and changed it a little bit, so to make it work inside of a function and this is the one I messed with the most in order to do this. But I kind of walked through Why and how I did that. So we come back over here then and we go to our post on we just check some data here. We can hit, submit data was successfully inserted. And if we go over here, you can see there's our data right here. Okay, so that's just cleaning it up a little bit so that Ah, this page over here is a lot cleaner. It doesn't have big hunks of code. It's a little bit more efficient. Um, a little bit more reusable and so forth. There's probably some other things that we could do in here, but I think for what we're doing here, this is probably sufficient, obviously. You know, if you use this and you use it over and over, you might develop some things that make it a little bit easier for you. But all in all, pretty pretty clean at this point. All right, That will do it for this lesson. Thanks for watching. We'll talk to next time 6. How to Display Your Data: Hey there, John Morris Here. John Morris, online dot column. This lesson. We're gonna talk about displaying our data from our database. So see, over here on the right hand side, I have kind of this simple little display table here of data that we have in our database. Come over here to our database. You can see the data in here mirrors what we're getting on our site, and so I'm gonna show you how we do that. Also gonna talk a little bit about the security part of this. So the first thing I've added a function over here in our functions file. This is actually the security part of this. This is a function. It's underscore. E basically stands for echo. And basically, what this does is it runs you pass a string into Iran that string through HTML entities with these flags so and quotes is going to escape both single and double quotes. And h t ent html five is gonna display code as HTML five. So and, ah, the character set here for this is utf eight, which we happen to be using here. So? So I would say fairly standard kind of thing. to do here. Um, the basic idea here is you'll see here, right here. This job script. Let me reload this page. Now, if I weren't doing the sanitization I was doing on the front end escaping that I'm doing on the back end here, then this When we loaded this page, this code would actually run. Okay? And if we ah, view the frame source here real quick, you can see the reason it doesn't is because it's actually all of the eight. The special characters and so forth have been turned into HTML entities. So this is how they're actually printed on the code in the source code so that when they display, they splay like this instead of like, for example, this javascript not displaying and actually rendering and processing like javascript. If you were to write it in your source code would Okay, so that's that's essentially how you you deal with cross site scripting attacks again. We're also like I mentioned doing sanitization on the front end. So that's part of it. We're also doing escaping on the back end that continues gives us another layer. Those two layers together gonna help prevent this sort of thing help people keep people from being able to inject javascript into your applications and have a process when you display your data. So that's the function I've added here. And that's really the security part of this whole whole part of this thing. From there, we just can get into how we actually get the data. So we again have our require once for our load, we have our standard sort of html header. Here. I did a body style actually made this one a little bit wider. You remember from our form, it was looks, I think, 500 pixels. I just did a in line style here to make this a little bit whiter. Probably, you know, not necessarily the best thing to do. She could maybe go about, um, you know, actually giving this this body tag a class on the stashing. Anyway, I didn't want to go through that. Ah, just for this purpose is So I just made a little bit wider there, and then we get into our actual code to to select from our database. So, um, we connect to the database, so we knew, instance, my school, I kind of like we've been doing. So our host user pass and database name and then we here because we're selecting all the data from a particular table and there's no user inputted data when running this query. We actually just run this toe the query method. Now, if we have user input the data, you would want to use prepared statements, Um, as we've kind of done in the past. So in this particular case, because we're not I'm just running this year. But if you were to say, Let's say you want to display data from a particular user so you maybe did something like this user. I d. Ah equals, let's just say one, I think one. If we look at our databases in there, If so, let's say we wanted to do this now, Right now, we're not processing, so it's not going to do anything, But you might want to do something like where I d equals. And then, you know, kind of in the past, you might actually do get and get that user. I d like this. All right. Well, that's really unsecure and safe because that data in the U. R L anybody can go in there and change that. So what you would do is, like we've done, you would put in a place holder, and this would be my sequel. Prepare instead of query and then down here, and we'd actually make this ah, statement, and then we do statement blind Paramus. And in this case, this would be an imager, and we would use I'm not gonna do any. I mean, you would still want to filter this and stuff like we've done potentially depending on what the data is not going to do any of that here just to show you this quick. So we're gonna do our buying parameter on and steam and execute the this would run that sort of, Ah, that would run that statement. Then I think you have to run like, get results. Um, in order to get the result, and then you would loop through it just like this, but you would. Point is, is you would use prepared statements just like you have here. Okay. So Ah, you don't want to If you're going to do something like this, you don't want to Yeah. You inject the data you don't want to open yourself up to SQL injection. Okay, but again, because in this case, we're not doing We're not doing that. We're just clearing for all users. Then we are fine to kind of do what we're doing here so well hadn't reload this. Just make sure everything's good here. And so then once we have our data, then have our queer here and we have our data. Then we're going to run a while loop and we're going to, So this is a little tricky here, but ah, what we do here is when you run this query and this is the same true. That's why when I got to that point in, ah, with the prepared statements, I had to think about a little bit, and I didn't want to bog down the tutorial, but this actually returns a resource, okay? It doesn't return the actual array of data if you come here and you print out. This resource is not the array of data that you think that you would you might get Okay. See, it says my ascribe result object. It's his current field field. Countless. Like this isn't the data this just tells you about the data Okay. So when you run a query, whether use prepared statements or anything else what you actually get back is this resource object. Then you have to. This is basically my sequel telling you Hey, this is what the data looks like. This is where you can find the data. This is where you need to go fetch it from. Hey, well, then you gotta actually go fetch it. And if you just run, fetch, object like this, it's just gonna fetch kind of the first row. And so that's all you're gonna get back. Is that that first row? Well, we want all the rows. So what we're gonna do is we're gonna do a while loop and we're gonna loop through. Ah, and we're gonna fetch each row. And we're setting ro equal to the result of fetch object. So we're essentially what we're doing is we're going through each row Ah, in our results, that here and we're fetching it and and fetching it as an object. So we're going to get an object back, and we're storing that as an element in our array. Okay. And then we're a row in our array, and then we're taking each row, and we're putting it into this results array. Okay, so if we print our results now, after having done that, then what we get is what you would expect. Um, and yeah. See, now, that's because I have I didn't remember I didn't escape the data in there. I'm just printing it out raw. So that's why I got the JavaScript to process. So again, That's why escaping output is important. So you can see here we have an array, and inside of each, each row is an object. This is the data that you would kind of normally expect to get back. Okay, so that's what this does. To be honest with you, it doesn't even really matter if you understand this necessarily because you pretty much any data where you're you're expecting to get something back where you're doing a select statement. Essentially, you're gonna have to do this, And it's really pretty much the same code every time. So just kind of write that cone down or use that code or put that somewhere because you're gonna be using this over and over and over again. Okay, so that gets us our array. That were kind of looking for here. And then now we have to build our table. So in our table are header section and our footer section here Will they stay the same? So we build those manually, just like you would kind of any regular table. So table T head, table, row, table header for each item. I mean, this is standard table stuff in here. It's just t foot than table, row, table header for each item. Okay, so his team standard kind of table stuff each to most stuff here in the body is where we actually have to loop through. And so here we're doing a four each, and we're going through our results set here and for each results. As a result, then we're going to build a row. So we're going to build one row for each record, and then each cell in that row is going to contain our data that matches up with what we put in our head or so Name, email, frequency interests, country comment, etcetera. Okay. And you'll see we're running each one of these through this underscore e. That's why when I printed this out just directly and I had that Java script in there. It it echoed it. It actually ran the JavaScript. Whereas when I don't do that right, if I just run this how it is, it doesn't do that. It prints it like this. So again, that's ah, really perfect. Great example of why you need to escape your data when you output it. And you know that Java script in this case is just on alert. But that Java script could be anything, so it could do all sorts of nefarious stuff on the person who for the person loads this page. That's why you want to do that. But here we're just echoing out essentially each each item from our ah from our column from our database here. So name, email, frequency, interest, country comment. So that's all we're doing over here. The one that's a little bit trickier here is, as we mentioned, kind of have alluded to is our interests area because they are stored in our database as serialized a raise. So the first thing that we have to do is we have to un serialize those Now I have this all together, but you can see I have results interests here instead of just echoing it out. I'm actually un serializing at first, so we're un serializing it. That turns it into an array. But we still can't just we can't, you know, we want to have it be user friendly to read. So we're not just gonna print out the array. So what we do is use implode, and so implode does is it takes the elements of Honore and turns them into a string using some sort of delimit er that you specify. And here we're specifying a comma and then a space. So essentially, it's gonna take the value of each array. So this thing particular example Element one in our ray was PHP element to is each to my literal element. Zero was PHP um that one was each to melon element to a CSS. It's taking those values each one of those, and it's mashing them into a string. But it's putting a comma and then a space between each one. So basically takes your rain, turns it into a string that you can then just echo. And so that's what we're doing here echoing that out. And the rest is just standard country comment. We're echoing all that stuff out. So that's how we go through. And we actually grab our data and then in this case, loop through on build a table with it. Now, of course, you don't wanna have, you know, user user data sensitive unit. That is just a wide open to the public like this. And there's a whole kind of other arena that we could talk about in terms of having a place to log in, to be able to do this and all those sorts of thing. But this is just a straightforward example of how you actually go in and grab that dad out and then put it into some sort of results table for you to look at. So that's pretty much it is straight forward as that Not not really a ton to it. And again, as I've kind of mentioned really important that you use that Ah, html entities. Otherwise you're gonna open yourself up to people Bajammal post all sorts of Java script just kind of willy nilly all over your site. So all right, that will do it for this lesson. Thanks for watching. We'll talk to next time 7. Next Steps: I'm honest there's no more. So online.com, so little housekeeping to finish up this course. If you haven't yet, be sure to head on over to the class area. There is a class section for some, some steps for you to walk through for this course. So be sure to head over in that it's under the discussion in Projects tab that you'll see on the course. Also, if you head over to my profile, be sure to give me a follow on my profile here so you'll be notified when I release new courses. And I also have an ongoing sort of weekly podcast style course called Let's Talk freelance. So if you would like to have sort of access to ongoing training regarding freelancing and online business and so forth. Be sure to check out that. Let's talk freelance course as well. And finally, I do have a daily tips newsletter on my website at John Morris online.com. If you head over there, you can sign up to that mailing list. You will also be put into my own, my very own mobile app, or you'll get access to over 78 hours of free content at the time of this recording related to freelance and so forth as well. So if you're interested in that, BD sure to check that out as well. Again, that's John Morris online.com. All right. Thank you for taking the class. If you enjoyed it, I appreciate you for You. Leave me a review and we'll see you in the next course.