PHP Full Course for non-haters 🐘 (2023)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everybody it's your bro hope you're doing well and in today's video I'm going to teach you guys everything you need to know to get started working with PHP so sit back relax and enjoy the show if you would like to be notified if I release new courses in the future be sure to subscribe because I kind of release them randomly that is all PHP is a server-side scripting language it's used to build Dynamic web pages it runs on a server not the user's web browser although haters say PHP is dead it's still used on 70 percent of all known websites I don't know that doesn't sound dead to me many developers prefer PHP for its speed Simplicity and flexibility it's a popular choice for small businesses and Freelancers especially since in the news lately you hear about layoffs in the tech industry PHP was released in 1995 it was originally an acronym for personal home page but that was later changed to PHP hypertext preprocessor to reflect the language's evolution in fact PHP was never intended to be a new programming language it grew organically and out of control until it became the Behemoth that it is today fun fact the mascot of PHP is an elephant which is named elephant Ella PHP find I don't know how I would describe the basics of PHP is as follows a browser sends a request to a server PHP on that server processes that request then the server sends HTML back to the browser our server running PHP can even communicate to a database then back to the web browser PHP is most commonly used with relational databases such as MySQL postgres and Oracle PHP can be written alongside with HTML before beginning the series you'll want to have a solid foundation on HTML you will need to know MySQL but that won't be until about video 20. for your web server I recommend zamp zamp is a cross-platform web server solution stack it's basically a software suite it contains an Apache server MySQL and PHP you'll also need some sort of text editor where are you going going to write the code vs code tends to be the most popular nowadays and that's what I use for my own personal projects we'll write our code with vs code then run our code on our xampp server since we can't run it on a web browser I'll show you how we can download both the xampp server and the vs code text editor now we will begin the installation process of a server that we can execute PHP code within go to this URL apachefriends.org like I said before PHP code is executed on a server and returned to a web browser click on one of the relevant download links for your operating system I'm running Windows I will download the windows version okay for me the installation process has started and it's done so let's open it for setup we're going to click next all we really need is MySQL and phpmyadmin it looks like PHP is already selected for us then next remember this file location my folder containing all of my zamp files is located in my C drive next you can select a language I'll pick English next and give it a minute do you want to start the control panel now we might as well and finish here is the control panel for my zamp server we will start the Apache service if everything works the Apache module is highlighted green that means it's working if you ever need to stop this module you can hit the stop button let's start MySQL as well and our MySQL server is working if you see any red text within this log that means there is an error if you run into any problems just check to see what that error was but everything for me is running fine this control panel will run behind the scenes I can close out of it but it's still running which is important hey this is bro from the future I forgot to mention in this video that if you ever shut down your computer you will have to open up the control panel again and restart these Services yeah I forgot to mention that so be sure to do that now that our xampp server is downloaded we will need that vs code text editor I'm assuming that some of you have that downloaded already but if you don't here's how if you need a text editor I recommend Visual Studio code if you're interested in downloading this text editor head to this URL code.visualstudio.com I'm going to click this blue download button select the correct download link for my operating system I'm running Windows I will select this one then we will run this executable except the license agreement yes I did read it that fast you do have the option of selecting a destination location I'll keep it as the default next next I'll create a desktop icon then next and install we might as well launch vs code then finish I have vs code open along with the modern web browser I'm using Google Chrome in the series we're going to create a new file within our zamp folder so let's open a folder remember that file path for the zamp server that's where you're going to look for me that was in my C drive go to xampp under htdocs we're going to create a new folder new folder I'll name this folder website to contain my website stuff then I will select folder within my website folder I'm going to create a new file I will name this file index.php the reason that I'm naming this file index is because that is the default for a home page so we now have a PHP file in vs code If you're receiving a warning that states cannot validate since a PHP installation could not be found we need to validate the executable path of the PHP executable found within our xampp server to do that we're going to find our settings file it's a Json file PHP validate executable path edit in the settings Json file let me maximize this next to PHP validate executable path we need to find the file path to the PHP executable again within my C drive within my zamp folder go to PHP then copy this file path for the executable I'll right click go to properties copy this location close out of this window paste that executable path then add PHP dot EXE then these may have to be forward slashes let's save on Windows you can press Ctrl s to save close out of these settings and that warning goes away I also recommend a few extensions the first extension is PHP intellisense it should be this one it gives you access to a few tools that are useful for PHP development let's install that plugin then look up the live server extension it offers a live reload feature then lastly PHP server it allows you to serve your project with PHP those are the three extensions that I recommend alright we are now ready to get started in a web browser to access your xampp server you can type localhost as the URL this will bring you to the zamp dashboard we would like to access the website folder of the zamp server so let's add localhost slash the name of that folder website our PHP code will execute on the server and be returned to this web browser whatever the output is to write some PHP code Type left angle bracket question mark PHP wherever our PHP code ends type question mark right angle bracket our PHP code will be between these two angle brackets to display a message you can type Echo either single quotes or double quotes then a semicolon at the end a semicolon is kind of like the period at the end of a sentence in English I will type a message I like pizza to save you can go to the top file save or use the shortcut which I'll be using so for me that's Ctrl s if I were to reload this webpage it displays my message I like pizza to make your life a lot easier we can add a live server extension to your web browser currently I'm using Chrome to add a live server extension I'm going to go to settings extensions open Chrome web store then search live server and that should be this one add to Chrome ADD extension let's close out of these tabs I'm going to go to extensions select live server web extension enable live reload we'll need the actual server address as well as your live server address this URL is the actual server address if you're on a Mac it may contain a port number such as 8080. so let's copy this address go to extensions then add the actual server address now we need the live server address to find this we can go to vs code press this go live button there should be a new tab that pops up copy this address that is the live server address then we will paste it within the live server address of this live server web extension then press apply you may need to restart your web browser as well all right that was localhost Slash website you know what I don't just like pizza I love pizza if I were to save this file it should update automatically see within our website it now says I love pizza let's add a second line with Echo Echo double quotes add a semicolon to the end let's add another line it's really good the output is all on one line to add a line break within your set of quotes you can add a Break Tag I love pizza it's really good to add a comment a comment is used as a note for yourself or other Developers all you have to type is double forward slashes then some message this is a comment our comment is not displayed as output it's mostly just used for notes for a multi-line comment you would type forward slash asterisk that will begin a multi-line comment this is a multi-line [Music] comment the end of our PHP script is currently green that means it's being included within this multi-line comment wherever you need your multi-line comment to end you would type asterisk then forward slash the end of the script is blue again and you can see that this multi-line comment isn't being displayed as output now the cool thing about PHP files is that they can contain HTML CSS JavaScript and well of course PHP so I will also include some HTML code within this PHP file so in vs code to generate some boilerplate code you can type exclamation point and then tab we now have some HTML markup within our PHP file within the body of our document I'll add maybe a button I'll create a button to order a pizza I should probably precede this button with a line break so there's our button it currently doesn't do anything but that's just a demonstration that you can include more than just PHP code within a PHP file alright everybody so that is an introduction to PHP in the next video we'll discuss variables hey if you're enjoying this video please let me know by Smashing that like button leave a random comment down below and subscribe if you'd like to become a fellow bro well hello everybody Welcome to lesson two today I'm going to discuss variables in PHP a variable think of it as a reusable container that holds data we give that container a name that is the variable name there's different data types we'll discuss they include but are not limited to Strings integers floats and booleans there are still more than this but these are a few of the basics for beginners let's get started to declare a variable you type a dollar sign then a unique variable name I'm going to store a user's name a unique identifier could be just name I will set this variable name equal to a string of text so place your string of text within a set of double quotes add a semicolon to the end because we always do that why don't you enter in your first name then to display this variable as output we can type our Echo statement then add the variable name so type dollar sign name semicolon let's save and there is our name rendered as HTML the data type of this variable is a string it's a string of text and it can include spaces add a space followed by your last name as I'll put we're displaying my first name and my last name all as one long string of text if you Echo a message directly that is known as a string literal I will display a message such as hello then I want to add this variable name the easiest way to do that is to add a set of curly braces as a placeholder and within the curly braces add your variable name so dollar sign name hello whatever your name is let's add a few more variables how about a food variable what's the food you like I like pizza of course which we learned from the last video hello name I'll display another message Echo you like at our placeholder our variable name food let's save I'm going to disable this page is not in Dutch for some reason our output is all on one line I'm just going to add a line break a low bro code you like pizza what's another example of a string maybe an email let's declare our variable which we will name email add a set of quotes semicolon to the end uh fake at gmail.com so let's add another line break let's Echo your email is at our placeholder for a variable then our variable name email your email is fake gmail.com that's the string data type it's just a series of text your text can contain numbers such as fake123 gmail.com so even though these are numbers we treat them more as characters we can't use these for any sort of math that's where our next data type comes in integers whole integers an example of a whole integer would be somebody's age let's say that I'm 21 age equals 21. I'm not 21 anymore but I like to think that I still am the data contained within this variable age is an integer we don't have any quotes around this number I will Echo my age variable Echo you are our variable age years old let me add a blind break here there you are 21 years old and int is simply a whole integer you know somebody wouldn't be like half a year old like 21.5 and age would be a whole number another example of a whole integer variable could be users let's create a variable named users and there are maybe two users online you wouldn't have half a user users would be a whole number let's Echo the amount of users there are at a placeholder our variable users online there are two online after the variable users let's add the word users there are two users online one more example of a whole integer could be a quantity you wouldn't have half a product you would have a whole product let's create a variable named quantity I'll just set it to three let's Echo you would like to buy are variable quantity items then a line break you would like to buy three items okay those are whole integers let's discuss floats next a float is a floating Point number it's a number that contains a decimal portion these variables are ins integers they're whole numbers an example of a float could be a grade point average maybe my grade point average is 2.5 so let's Echo your GPA is then our GPA variable then line break your GPA is 2.5 I think we're getting the hang of this I'm going to speed things up another float could be a price with a merry concurrency a price contains dollars and cents with the cents being a decimal portion suppose a pizza is 4.99 let's Echo your Pizza is I'll add my price variable your pizza is price line break your pizza is 4.99 I'm going to add the dollar sign before 4.99 but we have a problem PHP is getting confused because we precede our variable names with the dollar sign undefined variable 4.99 if you would like to display a dollar sign as output you need an escape sequence I will precede my dollar sign with a backslash then it works just fine let me add your your pizza is 4.99 so that's another example of a floating Point number a float another could be a tax rate tax rate I'll make up a tax rate like a sales tax rate 5.1 sounds good let's Echo the sales tax rate is tax rate oop I'm forgetting a dollar sign tax rate percent then a line break the sales tax rate is 5.1 percent those are floats floating Point numbers they're numbers that contain a decimal portion integers are whole numbers the last data type we'll cover are booleans booleans are either true or they're false it's like a light switch it can only be on or off so what are some variables that could be considered booleans what if somebody is employed they either are employed or they're not employed equals true I know there could be online is somebody online or offline maybe a user's offline I will set that to be false what about for sale something is for sale or it's not for sale I'll set that to be true now with booleans when you display them as output you don't see true or false rather this is what you see let's Echo online status colon then I'll add my Boolean variable online so online is false online status and then nothing appears the Boolean values when you output them if it's false it doesn't display anything however if online was true that will output a one one means true zero means false however we won't display zero nothing is displayed for false usually with Boolean variables we don't normally display them as output we use them internally within a program we might use these within an if statement or a loop which we'll discuss in the future but at this point you should be aware of the existence of Boolean variables in summary a Boolean variable is either true or false I'm going to get rid of these Echo statements you can mix and match variables when you display output with Echo I will add two variables this time here's a hypothetical situation you own a pizza restaurant and somebody places an online order for a given amount of pizzas you have ordered let's add our variable quantity X then our variable food you have ordered three x Pizza let's add an S to the end to make it plural you have ordered three x pizzas then let's calculate a total what I'm going to do now is declare a variable but I'm not going to assign it a value quite yet we will calculate a total total equals null no means no value We'll add a value later after displaying our message you have ordered quantity X food let's reassign our total variable equal to our quantity times to use multiplication use an asterisk our variable price so now our total should contain a number let's output it Echo your total is let's add our variable total and see what we have ooh I need a line break I'm forgetting about that you have ordered three x pizzas your total is 14.97 So I need to add a dollar sign or you can pick some other unit of currency however PHP is currently confused because we're preceding our placeholder with a dollar sign so I need to use an escape sequence your total is 14.97 now in my program if I were to change the quantity well this total is going to be updated four pizzas is 19.96 if I were to change the price that would also be reflected now the total is 23.96 all right everybody so those are variables they are just a named container for storing reusable data there are a few different data types strings which are a series of text ins which are whole integers floats which are floating Point numbers and booleans which are either true or false in the next topic we'll have more practice with arithmetic and PHP and well those are variables in PHP hello everybody so in today's topic I'm going to be discussing some basic arithmetic and PHP I'll divide this video into different sections first we have arithmetic operators then the increment and decrement operators followed by operator precedence let's begin with arithmetic operators in my example we have three variables X X will equal a number like 10. then we have Y which I'll set to be two then Z we'll assign z a value later I will set that to be null if I would like to add X and Y together then store the result within Z we'll have to use some addition I could write something like this Z equals our variable X Plus our variable y then I will Echo whatever Z is so 10 plus 2 that's 12. so that's addition I'll go through these pretty quick they're fairly straightforward so 10 minus y would be subtraction x minus y store the results in z the result is eight now multiplication that is an asterisk 10 times 2 is 20. division is a forward slash 10 divided by 2 that is 5. to raise a base to a given power you use double asterisks 10 to the power of 2 is 100 10 times 10 is 100. then we have the modulus operator that will give you the remainder of any division X modulus y well 10 divides by 2 evenly the remainder is zero if y was 3 imagine that we have a group of 10 students and they need to break into groups of three there's going to be one student that's remaining so the percent sign the modulus operator gives you the remainder of any division it's really helpful for determining if a number is even or odd you would just say modulus too if the remainder is 1 that number is odd if it's zero then it's even so those are basic arithmetic operators now we'll cover increment and decrement operators I have a variable which we will name counter I will set counter to be 0 to begin with if I need to increment this variable by 1 as if we're counting normally I would have to write an expression such as this our counter equals our counter plus one then let's Echo our counter variable so the result is one this can be cumbersome to write a shortcut you could do if incrementing a variable by one is replace this part of our expression with plus plus take the variable then add plus plus that will increment your variable by one plus plus is the increment operator for decrement you would use minus minus our counter is now at negative one if I were to set our counter to 10 after decrementing it's now nine use plus plus to increment minus minus two decrement you can increment by a given value too if I would like to count by twos let's set counter to be zero instead of plus plus you would write plus equals then some number counter plus equals 2 will increment my variable by two plus equals three would be three on the flip side to decrement by a given value you would use minus equal some number so zero minus equals two will decrement my variable by two minus equals three would be well three so that is the increment and decrement operators lastly we have operator precedence given a complex arithmetic expression such as this example in which order do we solve each part of this expression we would begin with parentheses beginning from left to right if there's anything within parentheses we would solve that first for example with my expression let's Echo whatever the total currently is so the total for me is 2.999 beginning from left to right solve anything within parentheses first we currently don't have any parentheses then comes any exponents so beginning from left to right look for any exponents we do have five to the power of six let's see what that is five to the power of five do it a third time fourth time fifth time sixth time fifteen thousand six hundred twenty five beginning from left to right solve any multiplication division then modulus modulo is that the right term so we have addition subtraction here we go we have multiplication three times four that's twelve then we have division 12 divided by fifteen thousand six hundred twenty five is point zero zero zero seven six eight yeah then lastly addition and subtraction we have some addition one plus two is three three minus this number point zero zero zero seven six eight is our result 2.99232 that's operator precedence if you have a complex equation solve anything within parentheses first then any exponents multiplication division modulus then lastly addition and subtraction all right everybody in conclusion we have discussed arithmetic operators addition subtraction multiplication division exponents and modulus incremented decrement operators you can take a variable add plus plus to increment it or minus minus two decrement it then lastly operator precedence and well everybody that is basic arithmetic in PHP hey again everybody it's me and in today's topic I'm going to explain the get and post variables in PHP get and post are both special variables technically they're super Global variables but that's a topic for another day just think of them as special variables for now these variables are used to collect data from an HTML form if you have an opening form tag in HTML you can use the action attribute then send some data to some PHP file whatever you list here there's two different methods get and post they each have their own advantages and disadvantages which we'll discuss later for the time being before our PHP script let's create an HTML document in vs code to do that you would type exclamation point then hit tab then be sure to follow our HTML document with a PHP script then I'm going to open up a web browser in our HTML document we're going to create a form a user is going to type in a username a password then to log in they're going to hit a login button let's create that we'll need a label to begin with we'll need to close the label I'll add a line break the label will say user name then we'll add a text box use the input tag it's a self-closing tag add a line break within the input tag we will set the type to equal text because it's a text box then we will set the name to be user name let's copy our label and our text box paste these two lines again but change username to password this time the type will be password the name will be password so you can type something into your username if you were to type within the password box it should be hidden which is good then lastly We'll add a button we'll use a self-closing input tag the type will be submit it's a submit button the value is the text on the button let's set that to be a log in so we have a button but it currently doesn't do anything we will enclose all of our elements within a form tag be sure to open it then close it I will indent all of this within my opening form tag I will set the action attribute to be a file in which I want to send this data to I will send this data to the PHP script of the same file so my file is index.php I will list that here index.php if you had a separate PHP file you would just change the file name to reflect that or the file path then we will set the method attribute to be either get or post we'll begin with get so let's type in a username make up a password and this still doesn't do anything within our PHP script we're going to utilize the get variable because we're using the get method let's Echo then type dollar sign underscore the word get so get is a special type of variable it can hold more than one value if you're familiar with arrays it's technically an array within get we have both a username and a password I would like just the username to get just the username after the get variable add a set of square brackets then within a set of quotes type in the name of the information you're getting I would like the username let's see what happens I'm going to save type in a username make up a password login and there's my username now let's do this with the password as well Echo get password so let's refresh everything I'll make up a username type in a password there's my username there's my password I'm going to put my password on a new line I need a line break there's a couple different ways in which we can do this you can use some string concatenation one way to do that is to type dot followed by a line break within quotes I'll do that for the second line as well so that would work my preferred method is to do something like this I'm going to surround my get variable with quotes then add a set of curly braces around our get variable then add a line break bro make up a password log in there we are if using the get variable and you need to add a line break this is my preferred way although there's more than one way use whatever suits you now with get we have one problem if we were to take a look at the URL of this document when using the get method of a form any data sent over to a PHP form is appended to the URL username equals bro and password equals pizza123 there's no security because we're appending some sensitive information such as a password to the URL that's where post comes in I will change the method to post let's see what happens I'll type in my first name make up a password and login so we have an undefined array key if you're using the post method let's change get to be post make up a username type in a password log in there's my username there's my password and if I were to take a look at the URL my sensitive data isn't appended to the URL the post method is more secure than get but they each have their own advantages and disadvantages with the get method data is appended to the URL it's not secure I wouldn't pass any like usernames or passwords using a get method there's a character limit however with the get method bookmarking a page with values as possible get requests can be cached get tends to be better for a search page now with post data is packaged inside the body of the HTTP request it's more secure than get there's no data limit Pages involving a post request can't be bookmarked and the requests are not cached post tends to be better for submitting credentials like a username and a password any sensitive information so if security matters use post if it doesn't get might be better now let's cover an exercise let's clear our PHP form then within the body of our document we will create an order page for a restaurant we will Begin by creating a form we'll need a pair of form tags then be sure to close it within my opening form tag I will set the action attribute to be a file or a file location I will send this data to my index.php file for the method let's use post for my order form let's create a text box for a quantity I'll create a label I'll close it right away let's change the text to quantity then I'll add a line break we'll add a text box input the type is text the name will be quantity we'll use the input tag set the type attribute to B submit then value equals how about total we're calculating a total now within my PHP script let's say we have a food item I'll create a variable item equals make up some food like pizza we'll need a price price equals make up a price 5.99 sounds good then a quantity whatever the user is going to type in that is found within the post variable dollar sign underscore post add a set of square brackets semicolon but then the square brackets I would like the quantity now this is a personal choice what I like to do is that if I'm accessing the get or post super variable I like to store the result within a local variable so I'm going to create a quantity variable quantity equals whatever our quantity is from our HTML form I find caching one of these values within a local variable more convenient to work with so let's Echo a message like an order total you have ordered let's use our quantity to T X what's our item pizzas item I'll add s because it may be plural then we'll calculate a total Echo you know what let's create a total variable as well total I'll set that to be an old because we'll assign a value later total equals quantity times variable price then we'll Echo your total is add a placeholder our variable total then I will precede our placeholder with the dollar sign but we need to use that escape sequence all right let's save everything enter in a quantity I want three pizzas oh we need a line break as well you have ordered three x pizzas your total is 17.97 and if I were to look at the URL we're using the post method so our quantity is not going to be appended to the URL if I were to use get let's replace post with get do that here as well I'm going to type in three pizzas again hit total I can change the url to reflect a different quantity like maybe I want 30 pizzas then resubmit you have ordered 30 pizzas the grand total is 179.70 that's one of the reasons why post is more secure than get you can change the url to reflect a different value alright everybody so that is both the get and post variables in PHP hey if you're enjoying my Series so far let me know by Smashing that like button leave a random comment down below and subscribe if you'd like to become a fellow bro hey everybody in today's topic I'm going to explain a few useful math related functions in PHP that you might be interested in we'll need an HTML document followed by a PHP script we will enter in some user input via an HTML form so let's create a form in our HTML document open it close it we will set the action equal to B our index page index.php for the method let's use post let's create a label label close it the label will be X we'll have a user enter in a number then let's add an input tag it's a self-closing tag the type will be text the name will be X then we need a submit button input type equals submit for the value let's say total it's a total button that's good enough for now if I'm using the post super Global variable let's say we need X Type post add a set of square brackets we would like the value of x I will cache this value within a local variable within my PHP script for convenience variable x equals whatever value for x that we receive just so that we're sure that everything's working fine let's Echo whatever X's Echo X So currently there's nothing in there let's type three hit total and there's our number X which is three so here's a few math related functions you may be interested in the first is the absolute value function let's say we have a total variable as well I'll declare this variable but not assign it quite yet I'll set that to be null then later on in my program we can assign total of value total equals to find the absolute value of a number type abs for absolute value followed by a set of parentheses semicolon whatever number or variable you put within this function ABS it will return the absolute value of that number we can either put a number in here or a variable let's put an X so variable X then I will Echo our total so I'm going to save I'll type in negative four this should return positive four which it does negative 100.123 100.123 that is the absolute value function let's cover a few more we have the round function we can round a number let's assign total equal to use the round function then we will pass in our variable X so let's save again refresh that 3.14 rounded is 3. 3.99 would be 4. now to always round down you can use the floor function so let's copy this line replace round with floor we will always round down so 3.99 rounded is 3. 4.99 rounded down is 4. there's also seal meaning sealing which will always round up replace floor with seal let's save refresh everything 3.14 rounded up is 4 4.14 rounded up is 5. for this next example we'll need another number let's copy our label and our text box paste it replace x with Y here and here we'll need two numbers this time let's get whatever Y is so y equals within the post super Global variable we are looking for y we can use the power function to raise a base to a given power let's take our total variable equals power we'll need two numbers or two variables what is X raised to the power of Y so what is 2 to the power of 3. that would be eight two to the power of four is sixteen what about 3 to the power of 3 that is 27 3 to the power of four that is 81. that is the power function you can raise a base to a given power then we have square root I'm going to put that here total equals sqrt add a set of parentheses let's find the square root of x so we don't need Y in this case what is the square root of 100 that is 10. 144 that is 12. that's the square root function we will need three variables let's create another label and a text box the third number will be Z be sure to change the name too then we will create one more variable variable Z post Z then we have the max function total equals Max whatever values or variables you place within the max function the max function will give you the greatest value what is the maximum number between variables X y and z so let's save I'll refresh that one two three the highest number is three Thirty twenty ten the highest number is 30. then we do have the Min function which will give you the minimum what is the minimum number between 10 20 30. the minimum is 10. 3 2 1. the minimum is one that's the Min function the next function is an unusual one it is the pi function total equals Pi function so add a set of parentheses this will print 3.14 and the remaining digits of pi if you ever need Pi you can use the pi function the next one is pretty useful it is the random function total equals Rand this will give you a completely random number I think up to just over 2 billion within the parentheses of the Rand function you can list two numbers for a minimum and a maximum if you're rolling a six-sided dice the minimum would be one the maximum would be six so now we're generating a random number between one and six we can either raise the minimum or raise the maximum for a random number between 1 and 100 within the Rand function the first digit is one the second digit is one hundred so we have 10 85 17 84. if I were to raise the minimum let's say 90 we'll generate a random number between 90 and 100. maybe you could use this for a game now we're going to go over an exercise for this exercise we will have a user enter in a radius the radius of a circle using PHP we will calculate what the circumference would be the area and the volume if that radius is for a sphere so we will need to accept some user input we'll do that with an HTML form so within our HTML document let's create a form then close it the action will equal our index PHP file the method will be post we will need a label close it the label will be radius let's add a text box we need a self-closing input tag the type will be text the name will be radius because we're accepting a radius then a submit button input type equals submit for the value let's say calculate that's all we need within our PHP script let's create a local radius variable we will get the value from this text box via the post super Global variable let's access the post variable we are looking for the radius and now we have a radius we'll declare a circumference variable I think that's how to spell circumference that will be null to calculate the circumference of a circle we can follow this formula circumference equals 2 times Pi Pi we can use the pi function times our variable radius then let's Echo let's say circumference equals add a placeholder then insert our variable circumference let's say that this is in centimeters then I'll add a line break maybe the radius is five I'll calculate that the circumference is 31.4 and we have a lot of digits after there's one thing I'm going to change real quick I'm going to add a line break after our form for the radius let's say it's 10. I'm going to hit calculate here's our circumference 62.83 and some change centimeters we can use the round function to round to a given digit I would like to round to the second digit after the decimal before we display our output let's reassign circumference equal to use the round function then pass in our circumference but I'm going to make one change normally the round function will round a number to the nearest whole integer to round to a given digit add a comma then that digit place let's round to the second digit so our circumference is 62.83 centimeters let's also calculate the area and the volume we'll need a area variable I'll set that to be null to calculate the area let's set area equal to we'll need the pi function times our radius to the power of 2 we can use the power function enter in our radius to the power of 2. then we can round our area equals round within the round function enter in your area we would like to round to the second digit after the decimal then we will display the area area equals our area variable I think technically that should be centimeter squared so let's save I'll enter in a new radius okay so if our radius is 15 this time I'll calculate that with the radius of 15 their circumference is 94.25 centimeters the area is 706.86 centimeter squared now we'll calculate volume if the radius is for a sphere volume equals no volume equals here's the formula 4 divided by 3 times pi function times our radius to the power of 3 we can use the power function we are raising R radius to the power of three then we will take our volume and round to two decimal places volume comma 2. then we will display the result with Echo volume equals add a placeholder our volume centimeters I think that's cubed technically if our radius is 5 their circumference is 31.42 the area is 78.54 and the volume is 523.60 centimeters cubed all right everybody well I thought that would be some good practice with some math functions now we're a little more comfortable using them if you would like a copy of this code I'll post it in the comments section down below and well those are some useful math related functions in PHP hey welcome back everybody in today's video I'm going to discuss if statements in PHP with an if statement we have a condition if some condition is true we can do something we can run some code however if that condition is false then we don't do it here's a situation suppose we have a website but you have to be 18 years or older to enter we can write a program to check somebody's age let's say we have a variable age age will equal make up a number 21. to write a if statement I would type if then I'll need a condition within parentheses what are we checking let's check to see if our variable age is greater than or equal to 18 then after the set of parentheses add a set of curly braces if this condition is true we can execute some code if it's false we skip over this code so if our age is greater than or equal to 18 let's Echo you may enter this site so I'm going to save run this program you may enter the site what if this condition was false maybe my age is 15. in our if statement this condition is false that means we do not execute this code we skip over it as if it never even happened if you would rather do some other code at the end of your if statement you can add else then add a set of curly braces if this condition is false then skip over this code and execute the else statement instead let's Echo you must be 18 plus 2 enter let's save and here's our other message you must be 18 plus to enter if I were to change age to 21 something that's above or equal to 18 well we execute the first statement this portion of our if statement you may enter the site if this is true do this if not do this instead between if and else you can add else if else if add a set of parentheses and a set of curly braces if our condition is false we would then check any else if statements before resorting to the else statement let's also check if age is equal to zero double equals is the comparison operator you could check to see if two values are equal you don't want to use a single equal sign because that is the assignment operator PHP thinks you're assigning age to be zero use double equals for comparison if somebody's age is zero then let's Echo a different message you were just born I will set variable age to be zero save you were just born this condition was false we skip it this condition was true so we execute it we never reached the else statement however somebody types in negative one well then we resort to the else statement because both of these conditions are false let's change our else if statement let's say else if age is less than or equal to zero let's change this message that wasn't a valid age negative one is not a valid age just to be funny what if we said you were too old too old to enter this site I'll add another else if statement just to demonstrate that we can add multiple else if statements else if age is greater than or equal to 100. then we will Echo you are too old to enter this site if I were to set age to be 101 the result states that you may enter this site the reason that we're executing this if statement and not this else if statement is because starting from the top we check the if statement first if it's false we continue down the line until we reach else age is 101 since this statement is technically true we would execute this code then skip everything else the order of your if and else if statements does matter I'm going to move this section of code to the beginning and make it the if statement first let's check to see if somebody's age is greater than or equal to 100 I will change this section to be else if and that should work you are too old to enter the site you do need to pay attention to the order of your conditions I'll give you another example if statements also work with Boolean variables and values we have a variable adult adult will equal a Boolean value of either true or false let's set that to be true with your condition you can check to see if your variable is equal use double equals for comparison true or false if adult is equal to true then we will Echo you may enter this site adult is true you may enter the site if adult is false then nothing happens so let's add else Echo you must be an adult to enter you must be an adult to enter now there is a shorthand if you're using the comparison operator followed by a Boolean value you could just write the Boolean variable itself that is also valid and that's my preferred way of using Boolean variables within a condition if adult do something so let's set adult to be true you may enter the site if it's false you must be an adult to enter so that is the second example let's go over and exercise we will create a program to calculate somebody's pay including overtime we will need three variables hours I'll set that to be 40 to begin with they're working full-time a rate as in a rate of pay this person is making fifteen dollars per hour and then a weekly pay I will set that to be null to begin with depending on somebody's hours they may or may not make overtime pay or if they work zero hours they don't receive any pay this week first let's calculate their weekly pay if they work 40 hours or less if hours is less than or equal to 40 then we will calculate our weekly pay with this formula it's only hours times their rate rate of pay then at the end let's Echo you made at our placeholder this week within our placeholder let's display the weekly pay variable pick your unit of currency I'll use American dollars I'll need to add an escape sequence 40 times 15 I think that's 600. you made six hundred dollars this week if we worked 20 hours then we make half of that three hundred dollars what if somebody doesn't work this week you made zero dollars this week what if somebody enters in a negative amount of hours like negative one well somebody made negative money this week let's write a condition to prevent that let's add an if statement then change this statement to be an else if statement if somebody is ours are less than or equal to zero then let's set weekly pay to be zero just in case somebody enters in a negative amount of hours because you can't work a negative amount even if somebody enters in a negative number like negative one or negative 10 our message still displays zero which is what we want lastly let's calculate overtime pay we'll do this within an else statement here's the formula let's set weekly pay equal to the first 40 hours are going to be at the standard rate let's take our rate times 40. then we will add within a set of parentheses we need to calculate the overtime pay maybe an employee Works 50 hours this week let's take hours minus 40. I'm going to add another set of parentheses around this multiplied by rate times 1.5 because with overtime pay at least in the United States I believe you make one and a half times your pay your hourly rate of pay if an employee Works 50 hours this week their new weekly pay will be 825 dollars that is an exercise involving if statements and those are if statements in PHP Hello friends it's me again and in today's topic I'm going to explain logical operators in PHP there's three and or not they're used to combine conditional statements for example if we have a if statement we check a condition using these logical operators we can check more than one condition if using and if that were or we can check if at least one condition is true with the case with not we can reverse a condition if it's true it's now false if it's false it's now true more on that later we can make our conditional statements a little more sophisticated with logical operators here's an example we have a temperature we would like to check to see if our temperature Falls within a certain range let's say we have variable temp short for temperature this will be in Celsius because most of my viewers are from outside of the United States in the United States we use Fahrenheit but use whatever works for you let's say the temperature is 25 degrees Celsius let's write an if statement to check to see if our temperature Falls within a certain range if temp is greater than or equal to zero we'll start with one condition then let's Echo the weather is good our temp is 25 25 degrees Celsius the weather is good what if my temperature was 100 degrees Celsius well the weather is obviously not good right in fact the weather is horrible to make sure our temperature isn't above a certain number we can use the and logical operator which is a double ampersand if our temperature is equal to or above zero and our temperature is less than or equal to 30 30 degrees Celsius then the weather is good this statement is true but this one is false with the and logical operator both conditions must be true in order for us to execute this statement otherwise let's add an else Clause else Echo the weather is bad so 100 degrees Celsius that is not a good temperature the weather is bad what about negative 10 negative 10 degrees Celsius well the weather is still bad 15. the weather is good 15 Falls within our range 15 is greater than or equal to zero and 15 is less than or equal to 30. Now using the orological operator which is two vertical bars at least one of these conditions needs to be true if we're writing the same program using the orological operator this is what I would change let's say if temp is less than zero or temp is greater than 30 then the weather is bad else the weather is good let's change temp to negative 1 million well the weather is bad if our temperature was positive 1 million I believe that's actually a hundred million uh well the weather is obviously bad as well if our temperature is 25 then the weather is good with our temperature being this high this statement is false but this one is true using the orological operator only one of these conditions needs to be true that's another way in which you can write conditions you could use the orological operator use whatever is best for your situation okay let's set temp to something reasonable like 15. all right now I'm going to discuss the not logical operator let's add a variable cloudy this will be a Boolean variable it's either true or false let's set that to be true the temperature is 15 degrees Celsius and the sky is cloudy that's set to true using an if statement if we're checking a Boolean variable we could write cloudy is equal to true but if we're working with booleans we can just short this to if the Boolean variable name that's valid if it's cloudy let's Echo it's it's cloudy else Echo it's sunny let me add one line break line break line break and I think we're good the weather is good it's cloudy using the not to logical operator we can precede our condition with an exclamation point if this condition is true the notchological operator will reverse it essentially so if not cloudy that means it's sunny else it's cloudy so it's cloudy I will change cloudy to be false it's now sunny that's basically the not to logical operator it will reverse the state of your condition meaning you can check to see if something is not true let's go over some practice in this example let's say that your country has elections let's assume that it's a democratic nation in many countries you have to be 18 years or older to vote right I'm assuming maybe we have variable age set the sequel to whatever your age is let's say that I'm 25 this time and we have a Boolean variable named citizen and I will set that to be true we're going to use the and logical operator to see if we can vote so with an if statement if variable age is greater than or equal to 18. I'm in the United States in order to vote you have to be at least 18 years old if we're at least 18 years old and we're a U.S citizen citizen then let's Echo you can vote in my example I'm 25 I'm a citizen both these conditions are true that means I can vote else if one of these statements wasn't true then let's Echo you cannot vote let's say that I am 12 12 years old well I cannot vote I'm too young or if I was not a citizen citizen is false well I cannot vote either another way in which you could write this program is you could say this is a little more complex by the way if age is not greater than or equal to 18 or you are not a citizen then you cannot vote else you can vote I'm 18 but I'm not a citizen I cannot vote I'm 18 but I am a citizen you can vote I would probably stick with the previous example just because it's easier to read but this is another way in which we can use the notch logical operator and the or logical operator let's go over a last example just so that we really get the hang of this we're going to sell movie tickets we will have some Boolean variables we'll have a child variable I will set that to be false to begin with a senior I will set that to be false then a ticket price which I will set to be null to begin with if somebody's a child or a senior they get a discount if child or senior then the ticket price will be uh maybe ten dollars else ticket equals fifteen dollars that's quite a steep discount then at the end of our program let's Echo the ticket price is I'll add a placeholder add variable ticket pick a unit of currency I'll pick American dollars child is set to false we're not a child that's set to false we're not a senior that's set to false the ticket price is 15 the standard this is false or this is false that means we don't execute the statement we move on to the else statement if we were a child let's set that to be true then we get that discount the ticket price is ten dollars if we set child to be false but we're a senior I'll set that to be true we still get that discount all right everybody point being with logical operators there's many different ways in which we can check conditions there's and or not use whatever is best for your situation typically there's more than one way in which you can check a condition well everybody those are logical operators in PHP hey what's going on everybody so in today's video I need to explain switch statements a switch is a replacement to using many l-sif statements switches are more efficient and take less code to write compared to using many else if statements here is an example I have a letter grade a student's grade can be a b c d f or if their grade is invalid if we have an else statement that states that letter grade is not valid depending on what our grade is we will execute one of many statements if our grade is a then we will Echo you did great if it's B you did good see you did okay d you did poorly F you failed if we have a grade that isn't valid such as Pizza well that's not a grade Pizza is not a valid grade using many else if statements is fairly inefficient and it's a lot to write to I would like to propose a better solution and that is by using a switch which is the topic of this video to create a switch we will type switch add a set of parentheses then add a set of curly braces within the parentheses of the switch what would we like to examine let's examine our letter grade then we'll probably want to change our letter grade to something valid like a within the switch we're going to create cases one case for each match that we're looking up type case what are we comparing our grade to let's compare our grid to the letter A then add a colon if our grade matches this case we'll write some code what do we want to do let's Echo you did great after all of your code add break to break out of the switch this is the first case let's copy this case underneath it after the break statement let's paste it then we will have case b you did good let's copy this again KC you did okay then d you did poorly case f U failed our grade is currently in a you did great Let's test out case b you did good see you did okay d you did poorly F you failed what if we have a grade that isn't valid like pizza again well nothing happens there were no matching cases we simply exit the switch if none of these cases match you can add a default case type default I can't spell it right today if there are no matching cases what are we gonna do let's Echo some sort of message I'll add a placeholder our grade variable is not valid so Pizza is obviously not a letter grade Pizza is not valid there were no matching cases therefore we resulted to the default case the default case is kind of like the else statement now the reason that you have a break in here let me demonstrate is because you will break out of the switch what if we were missing these break statements temporarily I'm going to remove them let's say that our grade is B you did good you did okay you did poorly you failed B is not valid you need the break statement to break out of the switch wherever there's a match we will execute the code followed underneath then any subsequent code followed after so be sure to include those break statements unless you want to execute every statement afterwards in some cases that could be helpful but not for this one let's go over another example we're going to get the current date I'll create variable date to get the current date we will use the date function within the parentheses of the date function within a set of quotes Type L just to be sure it's working fine let's Echo our date for testing L will give you the day of the week currently for me it's Monday so let's place our date within a switch we'll create a switch parentheses curly braces we are examining our date then we'll need a case case Monday if today is Monday let's Echo I hate Mondays then break so it's Monday I will Echo I hate Mondays so let's copy this case paste it change Monday to Tuesday what can we say for Tuesday it is Taco Tuesday So currently for me it's still Monday just for testing purposes I am going to change our date after we get the current date I just want to be sure that our switch is working what if our date was Tuesday it is Taco Tuesday what if it's Wednesday the work week is half over let's change our case to be Wednesday the work week is half over Thursday it's almost the weekend change our date to be Thursday it's almost the weekend Friday the weekend is here the weekend is here Saturday time to party time to party then Sunday time to let's relax on Sunday time to relax it's optional but we could add a default case if there are no matching cases let's Echo our variable date is not a day let's change our date to something like pizza well Pizza is not a day so I'll remove this line depending on what day you're executing this code it will display a custom message depending on the day of the week like I said today for me it's Monday so my message prints I hate Mondays all right everybody in conclusion a switch is a replacement to using many lcip statements they're more efficient and take less code to write I would recommend a switch if you're checking some value or variable many times over and well everybody those are switches in PHP hey everybody in today's video I need to explain for Loops a for Loop will repeat some code a certain amount of times for example I will display the word hello hello then I will add a line break I can write code once then repeat it however many times that I want with the for Loop to create a for Loop Type 4 parentheses curly braces then place your code you want to be repeated Within These set of curly braces I would like to display the word hello a certain amount of times that's the nice thing about for Loops you can write code once then repeat it but we'll need to calculate how many times we're going to repeat it within the parentheses of the for Loop we can write up to three optional statements each separated with a semicolon the first statement is that we can create a counter it's as if we're assigning a variable a common naming convention for a counter is variable I I meaning index I can set this equal to zero to begin with the next statement is a stopping condition when this condition is no longer true we escape the for loop I would like to display the word hello five times my condition will be variable I is less than five once I is no longer less than 5 we will escape the third optional statement we can use to increment or decrement our counter after each iteration I will increment I by One I plus plus this code will be repeated five times here we are one two three four five instead of displaying the word hello let's display our index I then add a line break I currently holds our counter we set the counter to begin at zero and it will stop when I reaches five zero one two three four maybe we would like to start at one and continue as long as I is less than or equal to five then we're no longer beginning at zero we could change this condition to be ten we will count up to ten or one hundred we will count up to one hundred when you increment your variable you can increment by a different number like two I plus equals two we are now counting up by twos one three five seven if we change our counter to be two we'll start at two then count up by two or maybe we can count up by threes two five eight eleven now to decrement let's begin at 10 our counter will be at ten we'll continue this for loop as long as I is greater than zero then to decrement take I then add minus minus so now we begin at 10 and decrement by one during each iteration or we can even decrement by twos I minus equals two so we begin at ten and we're decrementing by twos so that's a for Loop you repeat some code a certain amount of times there are three optional statements within the for Loop a counter we can declare a condition then we can increment our counter by a certain amount or decrement let's go over an exercise we will create an HTML form in vs code hit exclamation point tab that will generate some HTML code we'll create a form the opening form tag will have an action attribute of our PHP page index.php the method let's assign to post we'll create a label label close it enter a number two count two we will add a text box input type the type is text the name will be counter then a submit button input type equals submit for the value let's say start the user is going to type in a number to count up to we'll need to get that value from the text box let's say variable counter we will access the post super Global variable we would like our counter then we'll create a for Loop four parentheses curly braces we'll need our index for our for Loop so variable I equals zero to begin with we're counting up our condition will be variable I is less than or equal to our counter then we will increment variable I by 1 during each iteration during each iteration let's Echo whatever variable I is then add a line break let's see what happens let's refresh this let's count up to ten I'll enter 10 Press Start then we count up to 10. if you would like to exclude zero we can set I to be one there we are we have counted up to ten or I could pick a different number like 100. Press Start we now count up to 100. now what we're going to do is count down from a number enter a number to count down from we're going to change our for Loop a little bit we will set our counter of I to equal the number that we receive our counter variable will continue as long as I is greater than zero then we will decrement I so let's save you might have to refresh let's count down from 10 Press Start and here we are we have started at 10 and we have counted down to one or I can enter a different number like 100 so we start at 100 then count down to one so that's a for Loop everybody you can repeat some code a certain amount of times you only have to write it once then repeat it however many times that you need and well everybody those are four Loops in PHP hey everybody it's me again today I'm going to explain while Loops in PHP with the while loop you can do some code infinitely while some condition remains true it's very similar to a for Loop but with the for Loop we intend to do some code a limited amount of times with the while loop it may be infinite there's a lot of overlap where you can use either a for Loop or a while loop here's how to create one type while parentheses curly braces within the parentheses we can set a condition let's say we have a counter variable we will count up to ten keep doing this code while counter is less than or equal to 10. another difference between a for Loop and a while loop is that with the while loop we don't have three statements we just have one with the for Loop you can create an index a condition and there's another statement to increment or decrement we don't have that with the while loop so we'll have to set that manually outside of the while loop let's say we have a counter counter will equal zero while counter is less than or equal to 10. let's increment our counter by one counter plus plus then let's Echo our counter variable then add a break so simple enough that should be less than 10. there we escape the while loop when this condition is no longer true it's very similar to a for Loop honestly in this situation I would probably stick with the for Loop because you're still doing something a limited amount of times while Loops tend to be better if you need to do something possibly infinitely let's say we have a stopwatch program we don't know when the user is going to stop the stopwatch we would need to keep on updating our stopwatch until the user presses stop so we could write a program like this instead suppose we have a variable seconds to keep track of the amount of seconds then a Boolean variable named running if our stopwatch is no longer running if somebody hits the stop button we will set that to be false our condition could be a while running is equal to true if this variable is a Boolean we can just shorten this to while running while our stopwatch is running update the time or something I haven't talked about the sleep function yet but we can make our program sleep for a given amount of seconds so let's pretend that we wait one second then after waiting one second let's increment seconds by one then Echo the current amount of seconds and I will add a break I wouldn't recommend running this code we're going to be stuck in what is known as an infinite loop our program has no way of stopping and it might crash your computer you can see that the time just goes on and on forever so let's stop that my computer might crash this code is going to run forever because we have no way of escaping this Loop if you have a while loop you'll want some way to break out of the while loop from inside of it I'm going to create a stop button foreign I now have a stop button let's stop that before it crashes now to escape out of this loop I could write some code like this I'm going to write an if statement I haven't discussed the is set function yet but we can check to see if a button is clicked or not I'm going to access our post variable and I have created a stop button with the name of stop if I click the stop button then let's set running to be false then we can escape out of the while loop else if the user doesn't press the stop button then let's Wait Another Second and update our timer so this program is going to continue until I hit the stop button and it broke there it stopped what you should remember from this is that a while loop will do some code possibly forever while some condition is true you would need some way of making your condition false in this case I just set up a button to stop the timer there is a lot of overlap where you can use either a for Loop or a while loop if you need to do something a limited amount of times use a for Loop if you need to do something a possibly infinite amount of times a while loop might be better and well everybody those are while Loops in PHP why hello again everybody today I need to explain a raise in PHP think of an array as a special type of variable which can hold more than one value at a time in my example I have four different variables food one food two food three food four we have an apple orange banana coconut it can be very inconvenient to have to work with so many variables it would be really nice if I could store all of these values in one place which is what we can do with an array let's delete these variables we will create a special type of variable which is an array to create an array you'll need a variable name to begin with let's say Foods Foods equals to create an array type array add a set of parentheses then the semicolon at the end this is a function which we'll discuss more in the future whatever values you're going to squeeze into this variable just place them within the parentheses we had four variables Apple orange banana coconut separate all of your values with the comma there we go we now have what appears to be a variable but it's technically an array it stores more than one value in one convenient place if I was to Echo my array which I named Foods this is what happens warning a rate to string conversion we can't directly print this array instead you would need to access one of the elements an element is a given position within an array currently we have four elements because there's four values to access one of the elements found within your array after the array name add a set of square brackets then an element number with the raise the first element has an index of zero I would like the first element within my array so the element is going to be zero that will display Apple which is the first element in my array let's do this with the others for practice let's Echo Foods at index one I should probably add a line break so let me do some string concatenation real quick I'll add a line break do that here as well we have apple Orange let's do this with the others Foods at index two is banana Foods at index three that would be coconut what if I attempt to access an element that doesn't exist we only have four elements if I access our array Foods at index four well then we have a warning undefined array key for that is something you do need to pay attention to if you need to display all of the elements of an array there's an easier way of doing this instead of echoing every single element line by line we can use a for each Loop four each at a set of parentheses then a set of curly braces for each take your array Foods as now what we need is a temporary name for each element within the array my personal naming convention if I'm accessing a single element within an array I like to take the array name and set the variable name to be the singular version if we're working with Foods well each element is considered a food for every food in foods if we were working with different values let's say cars my for each Loop may be for every car in Cars but that's just my naming convention So within this for each loop I will Echo each food then I'll add a break line okay let's see what happens here are all the elements in our array to display all of the elements in your array a convenient way to do so is to use a for each Loop there are a lot of useful utilities related to arrays to change one of the elements of an array type the name of the array then we'll list an index number I would like to change the first element in this array to be a pineapple type the name of the array followed by a set of square brackets the first element in my array is zero I will set that to equal a new value Foods at index 0 is now a pineapple pineapple orange banana coconut there is a push function which will add a new element to the end of your array array underscore push function within the set of parentheses type in the name of your array comma then a value at the end of my array I would like to add a pineapple Apple orange banana coconut pineapple you can add more than one value too let's add a kiwi as well Apple orange banana coconut pineapple kiwi that is the array push function you can add one or more elements to the end of your array after you create one then we have the pop function array underscore pop pup will remove the last element in your array place your array name within the set of parentheses array pop Foods now we have apple orange banana our last element coconut was removed then we have shift array underscore shift shift will remove the first element in your array then shift all of the elements over by one within the set of parentheses list your array name we now have an orange banana coconut our Apple was removed it was shifted shifted out of the array we can reverse an array array underscore reverse place your array name within the set of parentheses now this isn't going to work I'll explain why our array is still in the same order Apple orange banana coconut this function returns a new array we can assign the result to a new array such as reversed Foods equals the array reverse function then I could display this our array is now reversed coconut banana orange Apple otherwise the array that's returned we can reassign it to the same array which is what I'll do that does the same thing if you would rather reuse the same array that is how to reverse an array we can count the elements in an array I will Echo use the count function place your array name within the function let me cut this real quick we have four elements within our array use the count function to get the current number of elements within your array all right everybody so that's an array think of it as a special type of variable that can hold more than one value at a time it's a convenient way to store multiple values that are similar or related in place of creating many different variables it's a lot easier to work with an array than several variables and well everybody those are arrays in PHP hey welcome back everybody today I'm going to explain associative arrays it's an array where each element is a key value pair for example we can make an array where each element is a country that's the key and the value is a capital A few other examples could be an ID and a username or an item and a price these would be examples of key value pairs here's an example let's start with a basic array I will create an array of capitals capitals equals we will use the array function we'll begin with keys each key needs to be unique I'll think of four examples we have the USA Japan South Korea then maybe India right now capitals is an array it's not an associative array to change this array into an associative array after each key add an arrow for readability I'm going to place each element on a new line it's not necessary but it's a lot easier for me to read following the arrow we will give each key a value the value in this example will be each country's respective Capital the capital of the USA is Washington DC Japan that's Kyoto South Korea that is Seoul India new Delhi we now have an associative array it's made of key value pairs if you need one of the values at a given key we would then access our associative array capitals at index then place your key within the set of square brackets let's find the capital of the USA then let's Echo whatever the result is and the result is Washington DC if I change the key to Japan we will be given the value at this key of Japan to print all of the key value pairs of our associative array we'll use a for each Loop within the parentheses we're going to write something a little different first we need our associative array capitals as key Arrow value this for each Loop will Loop through all of the key value pairs let's print them Echo I'll add a placeholder let's print each key and each value then I'll add a break line here are the keys and here are the values I'll add an equal sign before key and value just so it's more readable that's how to use a for each Loop to Loop through all the key value pairs in this associative array to change one of the values we need to access this array by a key I'll change the capital of the USA to be maybe Las Vegas let's take our associative array then I would like to access using square brackets USA set this equal to some new value the new value will be Las Vegas when I run this program the value at this key is now Las Vegas that's how to update a key value pair First Look up the key then you can set the value equal to some new value to add a new key value pair we will access our associative array add a set of square brackets then place a new key within a set of quotes within the square brackets let's add China will equal Beijing there's our new key value pair the key is China the value is Beijing the pop function will remove the last pair in this array array underscore pop we will pop our associative array capitals our pairing of India and New Delhi is gone that's how to remove the last pair in this array the shift function will remove the first element array shift pass in your array the USA and Washington DC pair is now gone it's shifted out of the array if you ever need all of the keys in this associative array there is an array Keys function array keys pass in your array of capitals this will return a new array I will assign that to a new array let's name it keys then I'm going to display all of the keys within our array using the for each Loop so let's change this a little bit we have an array of keys and I would like to display as key for every key in Keys let's Echo each key then I'll add a line break here are all of the keys within our associative array if you need the values instead there's a values function array values I'll create a new array named values for every value in values print each value and here are the Capitals all of the values within our associative array you can flip the keys and the values by using the flip function all right flip pass in your array within the set of parentheses this function will return a new associative array we can either create a new associative array or reassign it I'll reassign our associative array then we need to change our for each loop again so we have capitals as key Arrow value then we will display every key and every value key equals value our values are now switched with our keys the capitals are now the keys the countries are the values that is the array flip function if you need to reverse the order of your pairs you can use the reverse function array underscore reverse pass in your array this will return a new array I will reassign it the order in which we originally placed these key value pairs is now reversed India is now at the beginning the USA is now at the end then if you need the amount of key value pairs you can use the count function Echo count capitals let me get rid of this for each Loop to demonstrate we have four pairs within our associative array one two three four all right everybody so it's time for some practice I will delete everything but our associative array we'll create an HTML document so preceding our PHP script using vs code I will type an exclamation point then hit tab to create some sample HTML we'll create a text box a user is going to type in a country hit submit then we will return the value for that Associated country that capital we'll need a form form be sure to close it right away the action will equal index.php the method will be post let's create a label enter a country then we'll need a text box input type equals text the name will be country then a button input type equals submit here we are within our PHP script we have our associative array we'll need to access whatever's within this text box I'll store that within a new variable named Capital singular Capital equals dollar sign underscore post the value we are trying to access is the name country let's see what we have so far just for testing I'm going to Echo our capital if I type in USA then click submit this should return USA to get the value associated with this key USA I will take our associative array capitals at index of a country so in this example it's USA right I can copy this post variable delete this line within the set of quotes I will place the post variable then get rid of the quotes I will reassign Capital to equal whatever value we receive so I will type in this time Japan then this returns Kyoto we could even put this variable within a sentence the capital is our Capital variable if we type India then click submit the capital is New Delhi all right everybody so that's an associative array it's an array made of key value pairs you could create an associative array of countries and capitals ID numbers and usernames or items and a price those are a few examples and well everybody those are associative arrays in PHP hello again everybody today I need to explain two useful PHP functions the first is the is set function the other is the empty function these are two useful functions to determine if HTML elements are filled in or otherwise interacted with the isset function returns true if a variable is declared and not null empty returns true if a variable is not declared false null or is an empty string here's an example let's create a username variable username equals make up some username I am going to Echo then use the is set function Place some value or variable within the parentheses of this function when I run this program we output 1. in PHP one means true if user name was null is set returns false we don't display anything let's go over a few different values using an if statement if is set add a set of parentheses if the is set function returns true let's Echo this variable is set else let's Echo this variable is not set under which circumstances does the is set function return true that function returns true if a variable is declared and not null what if we don't have a variable the is set to function returns false that means we execute this else statement this variable is not set what if we declare a variable and it's null well the variable is not set either what if this value was true this variable is set how about false the variable is set an empty string the variable is set type in a username the variable is also set those are the circumstances in which the is set function will return either true or false now let's use the empty function this function will return true if a variable is not declared false null or an empty string let's change is set to the empty function we will examine our username variable if this variable is empty let's Echo this variable is empty else this variable is not empty if we don't have a variable I'll get rid of our username this variable is empty if username is null the variable is empty still true the variable is not empty false the variable is empty an empty string the variable is still empty type in a username the variable is not empty now what we're going to do is create an HTML login form we'll need a username a password and a login button we can use a combination of the is set and empty functions to determine if our login button is interacted with or our username and password fields are filled in so let's create an HTML document within the body of my document I will create a form then close it right away in the opening form tag we will set the action attribute to equal our PHP document the method let's use post we will need two labels one for username the other for password username let's copy this label paste it change username to password I'll add a text box [Music] the name attribute will be set to username I'll add a break line copy this text box paste it underneath password change text to password let's set the name attribute to be password then we need a submit button input type equals submit let's set the name equal to be let's set the name attribute to be a login then I will set the value the text on the button to be log in here's our sample login form using the post super Global variable is technically an associative array which we learned about in the last topic for demonstration purposes I am going to use a for each Loop and iterate over all of the elements within this array let's access our post super Global variable iterate over post as key Arrow value then during each iteration every key every value then add a break line I should probably add a break line after the submit button too you may need to reload your page then if I press log in we will spit out the associative array that's contained within our post super Global variable here are the keys and here are the values our username and password are both empty strings this thing our login key has this value whatever value we set within the HTML element if we hit the login button we can check to see if this key using the is set function we can determine if this value is set using the empty function we can determine if these values are empty which they currently are we can yell at the user like hey what the heck you didn't enter in your username or password I will reuse this for each Loop later let me just turn this into one giant comment now that we know how that works let's check to see if our button is clicked let's write an if statement if is set function access the post super Global variable we are looking for our login button whatever the name is set to for testing purposes let's Echo you tried to log in so if I save I need to reload the page if I press the login button this button is now set you tried to log in we no longer need this line for testing let's save after pressing the login button let's check if our username is filled in let's get the username username equals we are accessing the post super Global variable the key is our username whatever the name is then let's get our password to while we're at it variable password equals the key is password within our if statement we will write an inter if statement if empty function if our username is empty then let's Echo username is missing else we will display a welcome message Echo hello variable username okay let's reload [Music] I'm going to press log in without filling in a username username is missing but if I type in a username then log in we get our hello message hello bro code I'll add an else if statement then we'll check to see if our password is missing if empty function we are examining our password then we will Echo password is missing let's save reload type in a username don't type in a password Press login password is missing in order to Output this Hello message we need to both a username and a password type in a username type in a password Pizza one two three Press login and you get your welcome message I'm going to enclose the section of code within a comment block let's go back to our for each Loop there's something I want to explain so let's save reload make up a username type in a password when I press login you can see that our username and password fields are both filled in they're no longer empty this is our associative array contained within the post super Global variable using these if statements the first thing we were checking is if our login button is set which it is it contains a value then we were checking if our username and passwords were empty or not this time they were not empty that's what it looks like behind the scenes when you're accessing the post super Global variable it's made of key value Pairs and you can determine if a value is set or it's empty all right everybody so that is the is set and empty functions in PHP hey everybody in today's topic I'm going to show you how we can work with radio buttons in PHP let's get started to begin we'll need an HTML form I'm pretty sure you know how to create that already within our HTML form the action attribute will be set to our PHP file the method will be post to create a single radio button we can use a self-closing input tag set the type equal to B radio let's select a credit card I will set the first radio button to have a value of Visa here's our little radio button I'll add some text afterwards let's say Visa then I will add a line break okay let's copy these two lines of markup paste these twice then change the second radio button to be MasterCard then the third will be American Express so let's change these values here are three radio buttons but we have a problem we can select more than one radio button if we would like these within the same group we only ever should be able to select one at a time we need a name attribute name equals let's say credit card be sure to set this attribute for all of the three radio buttons they all need the same name there we can only select one now if these had a different name such as credit card 1 Credit Card two credit card three well they're technically all in different groups we need them all in the same group to select only one then lastly let's add a submit button input type equals submit the name may be confirmed it's a confirm button we're confirming some payment type for the value I will set that to be confirm as well now when I click on this button I would like to Output a message depending on which radio button is selected Let's test to see that everything's working fine though I will create a local variable named credit card I will set credit card equal to now to get one of these values we need to use the post variable whatever we set for the method access post the key we are looking for is credit card whatever the name attribute is set to the name of the group now when I run and reload this we have an undefined array key credit card which is to be expected we're running our PHP script but we have not yet set the credit card key let's enclose our code with an if statement we'll check to see if our confirm button is pressed is it set if it is then assign our variable if parentheses curly braces we will use the is set function which we learned about in the last topic we would like to check to see if our confirm button is set let's access post the key we are looking for is confirm whatever the name is if we press the button then assign our variable of credit card then let's Echo our credit card for testing purposes Echo credit card let's see what happens I'm going to press the confirm button then we get that warning which is a step in the right direction if I make a selection then press confirm we will Echo whatever value is stored within our credit card variable it's going to be one of these three values either Visa Mastercard or American Express before assigning the variable I would like this warning to not display after pressing the confirm button instead let's display a message please select a credit card or something let's create a nested if statement we will use the is set function again this time let's check to see if our credit card is set if our credit card is set then get the value and store it within a variable then for testing let's Echo that credit card if our credit card is not set we can execute an else statement else let's Echo please make a selection if I don't make a selection then press confirm we will Echo this message please make a selection in order to continue we need to make a selection let's select Visa we will output Visa MasterCard then American Express currently we have a variable credit card that has one of these three values one thing you could do with this variable is check to see if it's equal to a certain value I'm going to change my program around a little bit if we press the confirm button and one of these radio buttons is selected then assign our variable let's get rid of this Echo I'll add some if and else if statements this is just for demonstration purposes if our credit card is equal to Visa then let's Echo you selected Visa let's add an else if statement else if credit card is equal to MasterCard you selected MasterCard else if credit card is equal to American Express you selected American Express then else else if credit card doesn't equal one of these three matches then let's Echo please make a selection all right let's see what happens currently if I make a selection such as Visa we will Echo you selected Visa you selected MasterCard you selected American Express but currently if I press the confirm button without making a selection we have some warnings that our credit card variable is undefined but we still execute the else Clause as you can see here one change I'll make is that let's declare our variable credit card but we won't assign it a value credit card equals null then we won't receive that warning that credit card is undefined we have declared it I'll press confirm please make a selection I can select one of these credit cards and we will display a message in this circumstance I would probably use a switch where comparing some value against many matching cases I think a switch would be more efficient so let's create a switch for practice within our switch we are examining our credit card we will examine our credit card against matching cases Visa if our credit card is equal to Visa then let's Echo you selected Visa then add a break statement to break out of the switch let's do this for MasterCard add a case for MasterCard MasterCard you selected MasterCard then American Express American Express you selected American Express then a default case if there are no matching cases let's Echo please make a selection so if I press confirm we will Echo please make a selection if I select Visa you selected Visa you selected MasterCard you selected American Express all right everybody so those are a few different ways in which you can work with radio buttons in PHP to get the value of a given radio button group you can use the post variable then access that key whatever the name is then you can assign the value to a local variable to work with and you can do whatever you want with it in this case I just used a switch and well everybody those are a few different ways in which you can work with radio buttons in PHP well hello again everybody in today's video I'm going to show you how we can work with check boxes in PHP we need a form element I have the action attribute set to my PHP file index.php for the method I'm using post to create a checkbox we can use a self-closing input tag the type will be check box and here it is if we were to use post we will get a key value pair from this checkbox element the key will be equal to our name attribute let's say that the name is pizza and for the value let's say pizza I'm going to capitalize the value just so that it's easier to differentiate between the key and the value the name is the key the value as well the value then let's add some text Pizza brake element not sure why Google wants to translate this but okay let's copy these two lines of markup then paste them three additional times the second button will be hamburger the third will be hot dog the fourth will be taco let's change the names the values and the text the second checkbox is hamburger then hot dog then Taco here are the four check boxes then we'll need a submit button input type equals submit for the name that will be submit as well now within our PHP script when I press this button I would like to execute some code after we press the submit button I will enclose all of my code with an if statement we will check to see if our submit button is set we'll use the is set function we'll use the post variable we are accessing submit if we click the submit button then do stuff to check to see if a checkbox is set we can use the is set function again we'll use an if statement if is set now we are examining the key of pizza whatever the name attribute is set to if Pizza is set if it's checked what do we want to do let's simply Echo you like pizza when I press Pizza click submit we will display you like pizza let's do this with the other check boxes let's copy this if statement paste it three times then we'll check the other Keys we have hamburger you like hamburgers hot dog you like hot dogs Taco you like tacos oh then let me add a break after each of these sentences because I forgot to do that now I can press any combination of these check boxes if one of these check boxes is checked we'll execute one of these if statements you like pizza you like hot dogs you like tacos alternatively we can determine to see if a check box is empty using the empty function let's copy our if statements change is set to empty empty empty empty if Pizza is unchecked if it's empty we'll Echo you don't like pizza do this for hamburgers you don't like hamburgers hot dogs you don't like hot dogs and Tacos you don't like tacos if I were to click pizza and Tacos again then submit you like pizza you like tacos you don't like hamburgers you don't like hot dogs that's one way in which you can check to see if a check box is set you can use the is set function to determine if it's set or empty to determine if it's empty you can place all of these check boxes in an array but they would all need the same name attribute let's rename the name attribute to foods for all of these check boxes then add a set of straight brackets after each these will all be placed within an array let's get rid of our if statements after pressing the submit button let's create a Foods array then we will get via post the key name which is Foods Foods is technically going to be an array to prove it let's Echo Foods then see what happens Pizza hamburger hot dog taco warning a right to string conversion so Foods is an array we can access elements of an array with an index number Foods at index zero that would be Pizza one is hamburger two is hot dog three is Taco four should be out of bounds undefined array key for you can Loop through all of the elements of an array using a for each Loop for each list your array Foods as food then let's Echo each food then I will add a break Pizza hamburger hot dog taco all right everybody so that's how to work with check boxes in PHP the type set to checkbox the name attribute will be the key and the value as well the value you do have the option of placing all of these check boxes in the same group they would need the same name then add a set of square brackets after and well everybody that's how to work with check boxes and PHP hey everybody in today's video I'm going to explain how we can create functions in PHP with a function you write some code once then reuse it whenever you need it it's reusable code if you ever need to call a written function you type the function name followed by a set of parentheses for example we could have an add function we have a function name then two parentheses I like to think of the parentheses as two telephones talking to each other in order to invoke a function you call it like with the telephone some examples of functions could be add subtract multiply divide you can create all sorts of functions to do various things here's how to create a function we'll create a function to sing Happy Birthday to create a function type function then we're declaring a function name what would you like to name this function I will name it the happy birthday function add a set of parentheses a set of curly braces any code you would like to reuse you place within the set of curly braces I'll create some Happy Birthday song here's my function we write this code once then reuse it whenever we need it if I would like to execute the code within the function I would type the function name in this case it's happy birthday then add a set of parentheses like it's a pair of telephones talking to each other that's how you call a function and here's my birthday message um I forgot some break lines let me put those in real quick that's much better happy birthday dear you happy birthday to you happy birthday dear you you are X years old I know it's kind of a lame song I just made it up on the spot I can call this function as many times as I need it if I would like to sing Happy Birthday three times I would just invoke this function three times there we have sung three verses of happy birthday I'm gonna add another break statement though there so a function is just a section of reusable code you write it once reuse it whenever you need it with coding we try not to repeat code if we don't have to with a function you can send your function some data some values or variable I'm going to send my happy birthday function a string a first name let's say SpongeBob if you send your function some data a value or a variable this would be known as an argument we need a matching parameter a parameter is kind of like a temporary variable let's create a parameter named first name this parameter only exists within the scope of this function when you escape the function this variable no longer exists let's replace U with a placeholder then we will add our parameter our variable first name happy birthday dear first name let's do that here as well then let's try this again happy birthday dear SpongeBob happy birthday to you happy birthday dear SpongeBob you are X years old I could call this function again and pass on a different parameter like Patrick we have a verse of happy birthday but we have sent a different argument Patrick instead of SpongeBob let's do it one more time we will invoke happy birthday then pass in a first name Squidward happy birthday dear Squidward you can pass in more than one argument to a function let's send an age so separate each argument with a comma I don't know how old SpongeBob is according to the lore let's say that he's 30. let's do that with Patrick as well let's say he's 35 then Squidward he seems older maybe he'll be 45. we have two arguments when we invoke this function we should have two parameters for the second parameter let's store these values in a variable named age then we can use this variable for something let's replace x with variable age happy birthday dear SpongeBob you are 30 years old Patrick is 35 years old and Squidward is 45 years old that's how to invoke a function and pass arguments to it but you would need a matching set of parameters now with the function you can return something you'll typically see a return statement at the end of a function let's go over a different example we will create a function to check to see if a number is even or odd function let's name this function is even we will need one parameter a number to invoke this function you type the function name then add a set of parentheses if there's a parameter you need to pass in a value or a variable let's see if the number 11 is even now within our function we need to write some code let's say we have a variable result equals that to see if a number is even or odd you take that number or that variable modulus 2. modulus gives you the remainder of any Division if number divides by 2 evenly the results should be zero if it's odd the result is one then we'll use a return statement and return some value what would we like to return let's return the result now if I Echo after executing this function whatever is returned kinda takes its place then I'm just going to Echo it is 11 even or is it odd that returns one is 10 even or odd that returns zero it's even you could shorten this too let's get rid of our result variable take this section of code and we are returning whatever the outcome is that works too let's write something a little more complicated let's create a function to find the hypotenuse of a right triangle so let's define our function function let's name this function hypotenuse we'll need sides A and B as arguments so set up these matching parameters to find side C we need to follow this equation square root function variable a to the power of 2 plus variable B to the power of two then we will return whatever variable C is I'm going to invoke this function but we need two arguments side a and side B let's say side a is three side B is 4. now this doesn't print anything C should technically be five so after executing this function after it's complete just imagine that we're returning five so let's Echo whatever the result is or we could store it within a variable so now the result is five let's do two different numbers side a will be four side B will be five side C is six point four and some change one last thing I should mention with your parameter names you can declare a type that needs to be passed in for example if I was to send in like a string like find the hypotenuse of pizza and taco well that really doesn't make sense right fatal error uncut type error unsupported operand type string you can list a data type before the variable name to force the arguments to be of that data type I could say these need to be integers I would type int or float for floating Point numbers if I try this again we receive a different type of error uncut type error now I haven't discussed error handling yet but this will come in handy when we get to that point just be aware of that with parameters you can list a data type beforehand then you need to pass in an argument of that exact data type all right everybody so that's a function it's a section of reusable code whenever you would like to use this function you type the function name add a set of parentheses if there are parameter setup you need to pass in a matching set of arguments then you can return something and well everybody those are functions in PHP hey welcome back everybody in today's topic I'm going to explain a few useful string functions you might be interested in let's begin with creating a username assign this your first and last name the first function I'll discuss is the string to lower function I'm going to reassign our username and use the string to lower function then we will pass in our username as an argument then let's Echo our username after we make it lowercase Echo username there my username is all lowercase alternatively there's string to Upper string two upper my name is all uppercase then we have trim will remove any white spaces before or after your string there there's the string pad function we can pad a string up to a certain amount of characters with a character we specify let's say I would like to pad my username to a Max size of 20 characters with zeros here's my new username or maybe we could use forward slashes or something then we have string replace string replace within our string we can replace one character with another you know what let's create a new variable how about a phone number let's say phone phone equals make up some phone number 123-456-7890 here are the order of arguments what would we like to replace let's replace any dashes that'll be the first argument the second argument is what we're replacing the dashes with let's use an empty string then third is our string or variable containing a string we are reassigning our phone number here's our new phone number with all the dashes removed or we could replace them with something else like a forward slash that is the string replace function then we have string reverse s t r e v let's reverse our username then Echo our new username there it is it's all backwards then we have String Shuffle we can shuffle a string compare s-t-r-cmp we can compare a string or a variable against another string or variable I'll assign this to a new variable let's say equals so if these two strings are the same then this function will return zero if they're different we'll either return one or negative one think of it as if these two strings are the same string compare returns zero it returns false so that's how to see if two strings are equal then we have the string length function string length let's create a new variable count how many characters are within our string in my string we have eight characters one two three four five six seven eight let's do that with our phone number our phone number has 12 characters that is the string length function we can use the string position function to find the position of a character with my username let's find the first position of a space the character or string you're looking for is the second argument I'll create a new variable index so the index of the first space within my username is three zero one two three let's do that with our phone number then let's find the position of the first Dash which would be three as well zero one two three then we have the substring function sub string we can create a new string from a portion of another string with my username I'll take the first three characters and create a new string I'll create a variable named first name here are the order of arguments take your original string let's say our username the second argument is the starting index I would like to start at the beginning the index will be zero then an ending index I would like to end at this space in my name but if you're using your own first and last name you're going to have a different position so for me I'd like to end at the third index then I will echo my first name we have created a new string from an original string but we have to specify the beginning and ending index this time let's take the last four characters I'll create a new variable last name we'll use the substring function again username now you can list a beginning index and then don't specify an ending index then you'll create a new string all the way up to the end if I set my index to B4 we'll create a new substring with everything after the index of four no matter how long the string is so let's Echo our last name and there's my last name in my example so to get everything after the beginning index just don't list a third argument okay now we have the implode and explode functions with your username add your middle name or maiden name or whatever or a nickname doesn't matter just something we can use the explode function to assign each of these portions of our name into an array let's create an array named full name we will use the explode function we are exploding our username however at which character or characters do we separate each element in our array we'll do so by any spaces in this example so that will be the first argument explode our username let's see if this is actually an array let's Echo our full name warning array to string conversion so that's a good sign that means that our full name is an array you know what let's use a for each Loop to demonstrate for each take our array full name as name then I will Echo each name there here's my array and I've taken each portion of our name and placed them as elements within a new array now we have implode which takes an array and creates a string out of them a single string let's say our username is an array so type your full name then we will use the implode function username equals implode what are we imploding let's implode our username then you can add characters between each element I will add an empty space between each element when we implode it then let's Echo our username Echo username my array is all one long string now or maybe I can separate each element with a dash it's still one string alright everybody so those are a few useful string Methods I think you might be interested in in PHP hey everybody what's going on in today's video I'm going to show you how we can both sanitize and validate user input in PHP we're going to need an HTML form to work with I'll go ahead and create that here's my form we have a text box and a button when I click on the button we'll execute some code I will enclose all of my code with an if statement we will check to see if our login button is set if it's interacted with if set we're accessing post if our login button is interacted with let's get the username from the text box and store that within a local variable then let's Echo hello username so I can type in a username Press login and we are pretending to log in if you don't sanitize or validate your user input somebody could write some malicious code like a cross-site script or SQL injection such as this foreign what I did is just write some malicious JavaScript code to display you have a virus it would be best to prevent code like that from running one way in which we can do that is to add a filter to sanitize any user input instead of assigning our username directly from our post variable we are going to use a function the filter input function and there are three arguments the first argument is input post because we're using the post method if we were using get then this would be input get the second argument is the name of the input which in this case would be username then third is the type of filter I'll put this on a new line because I'm running out of room I would like to remove any special characters used in executing code so there is a filter for that it's filter sanitize special chars I'm going to take this JavaScript code paste it into my username and we'll see if we can execute this code which we cannot instead of executing the code we are using it as output and if I were to right click then go to view page source any special characters are replaced here is that JavaScript code I entered it's not executing because we filtered these special characters if you ever need to filter all characters besides numbers there is filter sanitize number int that's another filter let's create a new text box for an age age the name will be age so again let's create a new variable named age equals filter input input post because we're using post the name of the input is age then the type of filter sanitize number int let's create a new message you are variable age years old if I were to type in Press login we will filter all characters besides any numbers that is the filter sanitize number end filter now maybe we need an email let's create a new text box for an email the name will be email email equals again filter input the first argument is input post or input get if you're using get the name of the attribute is email the third argument is the type of filter sanitize email your email is variable email I'll type in an email then add some illegal characters for an email such as angle brackets and parentheses and this should filter all of the illegal characters which it does here's my email without those illegal characters so those are a few ways in which you can sanitize input now let's validate input using a validate filter if our input doesn't pass a validation test it returns an empty string sanitization will strip certain characters of user input validation if it doesn't pass it just returns an empty string so now we have variable age age equals we'll use filter input again input post because we're using post the name of the input we're filtering is age then the type of filter validate int if our user input isn't a number we will assign an empty string to age it doesn't pass the validation test so let's check that let's use an if statement we can use the empty function if our age is empty that means a user didn't type in a valid number let's Echo that number wasn't valid else if our age is not empty that means they typed in a valid number you are age years old let's run this again uh I'll type in a bunch of characters I'll try and log in uh that number wasn't valid I'm not surprised so now let's type in a valid number and that seems to work using this filter we can check to see if some input is only numbers the next filter is to validate an email to see if it's in a correct format let's copy these two lines of code paste them variable email input post we are getting our email user input filter validate email if our email is empty that email wasn't valid else your email is our variable email okay I'll make up some email Press login that seems to work I'll type in that same email but I'll add some illegal characters like angle brackets and parentheses that email wasn't valid all right everybody so those are a few filters you may be interested in when accepting user input it is a good idea to both sanitize and filter user input just in case a user types in some malicious script you don't want any of that sanitize and validate your user input whenever possible and well everybody that's how to both sanitize and validate user input in PHP well well well look who it is in today's topic I'm going to explain the include function the include function copies the content of a file and includes it in your PHP file a few of the benefits is that sections of your website can become reusable any changes only need to be made in one place for example we could create an HTML document for a header and a footer within each page of our website we can include that same header and footer that header and footer file become reusable here's an example we will create a few files our index file will be our home page let's create one for an about us page about dot PHP another four locations to list our locations for our imaginary business then we'll create an HTML file named header header.html then another named footer footer.html here are the files we'll be working with let's fill in our header file we'll create a standard header for a website for our header let's create a pair of header tags I'll add a title the title will be within a pair of H2 header tags this is my website then we'll create a few links for a navigation bar let's set the first link to have an href attribute equal to our home page which we named index.php be sure to close it the text will be home let's copy this link paste it two times the second link will be for our about page change the text to about then locations locations.php then change the text to locations I'll add a horizontal rule as well that is good enough for our header let's head back to our index file to use the include function within your PHP script let me write that PHP all we have to do is type include it's a function then list the file name or the file path these two files are in the same website folder I only need to include the file name header dot HTML then when I save and reload everything we have our header then I could add some HTML afterwards so let's generate some html text within the body of my HTML I'll add a few sentences this is the home page I'll add a break stuff about your home page and go here then let's add a footer let's go to our footer HTML file I will use a pair of footer tags to create a footer I'll add a horizontal rule let's say author colon space type in your first and last name then I'll add a link for an email at href equals mail to come up with some email I'll add some text then close the anchor tag that's good enough for our footer our footer and our header are now complete let me close out of those we have our index page our about page and our locations page after we display everything that we would like for the home page let's display the footer the footer belongs at the bottom of our web page so let's copy our PHP script after our HTML markup let's include our footer footer.html there it is our header and our footer are reusable we only need to write these once and we can reuse them for every web page with our about page let's generate some HTML I'm going to copy these two lines of our body this is the about page stuff about your about page can go here I'm going to click on the link for our about page but we don't have that header or footer so let's add a PHP script before and after to include those PHP we will use the include function we will include list the file name and or the file path header.html and there is our header do the same thing with the footer PHP we will use the include function we are including our footer footer.html and there is the footer of our web page so now we can navigate between our home page and our about page they're both two completely different pages they have different text but we're reusing the same header and footer okay let's finish this with our locations page I'm just going to copy all of this just to expedite everything this is the locations page stuff about your location page can go here okay let's click on our locations page and we are now within the locations page again we're reusing the same header and the same footer parts of our website are functioning as components they're reusable we don't need to create an individual header for every file for every PHP file we can write them once then simply reuse them the cool thing is too if we need to make any changes they'll be reflected across every web page let me change my email to at gmail.com see my email just changed and that is reflected on every web page it helps with code reusability then let's change our title let's go to our header this is the type in your name bro code website and that change has been reflected across all of our web pages that is the include function you can include the contents of a file inside of your web page it helps with reusability and if you need to make any changes you can do so in just one place and that is the include function in PHP hey everybody Welcome to the wonderful world of cookies a cookie if you don't know basically speaking it's information about a user stored in a user's web browser that's why you might receive targeted advertisements platforms such as YouTube they might remember your browsing preferences and you can store other non-sensitive data now to create a cookie in PHP we will use the set cookie function it's actually pretty simple our cookies are stored as an associative array first is the key our key will be favorite food the second element is the value my favorite food will be Pizza the third argument is an expiration time cookies typically expire after a certain amount of time to set the time we can use the time function then add this is in seconds for one day that would be 86 400 seconds if you need your cookie to expire after two days we can just multiply this by two then let me enclose these within parentheses just for clarity then the next argument is the file path I'll use a forward slash for the default file path and there we are so I'm going to save this now if we open up our web browser I'm going to right click go to inspect you can find your cookies underneath application then go to cookies underneath storage oh look at that we have a cookie the key is favorite food the value is pizza and there is an expiration date here too there it is let's add a few more cookies set cookie favorite drink I will set the value to be coffee this cookie will expire after three days there's our next cookie one more favorite dessert I will pick ice cream this cookie will expire after four days so 86 400 times 4. there we have three cookies favorite dessert favorite drink favorite food now to delete a cookie all you have to do is set the time to minus zero so let's do that for all of these yeah look at that the cookies are gone now let's revert that back and we have cookies again let's print each key value pair from all of our cookies I will use a for each Loop we are accessing the cookie super Global variable our cookies are stored as key value pairs using a for each Loop we can write as key Arrow value I will Echo each key value pair key equals value then a break here are the three cookies we set favorite food equals Pizza favorite drink equals coffee favorite dessert equals ice cream to access one of the values you would need the key maybe I will display an advertisement based on somebody's favorite food maybe we remember what their favorite food is I will use the is set function is set place it within an if statement we will check within our cookies add the key of favorite food if their favorite food key has a value let's display it buy some then let's access our cookie variable at the Key of favorite food okay else Echo I don't know your favorite food our cookie for our favorite food is currently set let me get rid of this for each Loop if our favorite food key has a value that's set will display an advertisement for their favorite food buy some pizza if this cookie wasn't set I'll let it expire by setting the time to minus zero I don't know your favorite food this cookie isn't set we will execute the else claws alright everybody so those are cookies they are just information about a user stored in a user's web browser these are used for targeted advertisements browsing preferences and other non-sensitive data and well everybody that's an introduction to cookies in PHP hey everybody how's it going in today's video I need to explain sessions in PHP because well it's an important topic in PHP a session is a super Global variable that's used to store information on a user to be used across multiple Pages once a session is created a user is assigned a session ID for example these can be used for login credentials once you log into a site like Facebook for example you can visit different pages on that site and stay logged in we'll do something like that with PHP let's get started we have our index PHP file but let's create another our index page will be our login page then we'll create a PHP page named home home.php the idea is that once we log in with our index file we will be redirected to our home page so we have two PHP files Now to create a session before you display any HTML we will use the session start function within my PHP script I will type session start and that's how to start a session then after you start a session then you can add any HTML let's generate some HTML I'll add some text to our HTML page this is the login page then I'll add a hyperlink for the home page we'll use an a tag set the href attribute to equal home dot PHP this goes to the home page then be sure to close it I'll add a break as well perfect after our HTML document let's add another PHP script we can create name value pairs within our session super Global variable let's create a key of username set this equal to a username of your choosing then let's do that with the password as well so we will access our session super Global variable we will create a key of password then make up some password for testing purposes let's Echo our username and our password Echo session we're accessing the key of username then we will be returned to the value then I'll add a break then do this with password as well let's see if this works okay here's my username here's my password they are stored within the session variable but we can access the values with a given key they're in key value pairs I would like these values to be accessible from another page from my home page for demonstration purposes I am going to Echo our username and our password from our home page but we need to create a PHP script so PHP then I will Echo our username and our password let's see what happens it's an experiment so I'm going to save everything on our index page we have our username and our password that works fine but if I were to go to our home page our second page well we don't have a username or a password undefined Global variable session within any additional files that we create we will also need to start a session with the session start function and I'll just copy this you'll need to do this before any HTML is displayed we'll start the session I'll create some HTML I'll copy these two lines but make a few changes to them okay this is the home page then I'll create a link to our index page this goes to the we'll call the login page let's reload this okay this is the home page this goes to the login page we do have our username and our password so I'm just switching between the home page and the login page we can access our session variable from either page as long as you start a session for some additional practice let's change our login page to actually reflect a login page we'll have a text box for both a username and a password and a login button so let's go to our index page so this is the login page let's change a few things around we'll create a form set the action attribute to equal index.php for the method since we're using credentials we should use post let's say username add a line break I guess that can be a label too we'll need a text box input type equals text for the name attribute let's set that to be username add a break let's copy these two lines of markup then paste them change the second username to be password also do that with the name attribute then we need a login button input type equals submit for the name this will be login for the value let's say that this is login as well then let's get rid of these lines I'm going to minimize this Explorer window just so we have more room to work with what we're going to do now is after somebody clicks the login button then we'll assign our session variable to check to see if somebody interacts with our login button we can use the is set function within an if statement if is set let me scroll down a little bit we are accessing our post variable at the Key of login if this button is interacted with if it's set we will assign our session variable we'll create a key of username we will assign whatever is within our text box for our username in a real world scenario I would probably use a filter but just for learning purposes I'm going to keep it simple and not use one maybe in a project we will I need to access our post variable at the Key of username whatever's in our text box we will assign to our session variable of username then do that with our password as well before we log in we have to check to see if our username and our password fields are empty we could write using an if statement if not empty function we are checking if our username is not empty and let's check to see if our password is not empty I'll put that down here if our username is not empty and our password is an empty then let's assign our session variables so for testing purposes let's Echo those values Echo the sessions username I'll add a break then do that with the password all right type in a username make up a password oop that should be a password Field hold on type equals password there we go here's our username here's our password if I were to refresh everything type in either a username or password we shouldn't display anything which is correct if one of these two fields are empty let's add an else clause let's Echo missing username slash password one of those is missing then I'll add a break I'll type in a username but not a password missing username slash password let's type in a password but not a username missing username slash password let's type in both and that seems to work now let's get rid of these Echo statements we no longer need them we were using them for testing purposes what we're going to do now is after hitting the login button we will redirect our browser to our home page there's a function for that it is the header function we'll add that right here after we assign our username and password to jump to our home page within the header function and within quotes we will type location colon space then the name of the page home.php home dot PHP let's save everything make sure you're on your login page I will type a username and a password Press login and we are directed to our home page we are still maintaining that session we have our username and our password still let's create a log out button we'll do this within our home page let's get rid of our hyperlink we'll create a form that just has a button so the action attribute will be home.php or the method let's use post again I will add a button the input type will be submit for the name this will be log out for the value that will be log out as well we will use the is set function to see if our log out button is set so let's use an if statement if is set is our log out button set we will access post the key is log out if this button is set we will use the session destroy function we would like to end our session if we're logging out we will use the session destroy function to destroy the session after logging out let's go back to our login page the index file we will use the header function again set the location to be index.php I will log out and that should bring me back to my login page alright everybody that's how to create a session in PHP you can store information about a user that can be used across multiple pages and well everybody that is an introduction to sessions in PHP hey everybody today we will be discussing the server super Global variable it contains headers paths and script locations it's an associative array that's created by the web server it contains nearly everything you need to know about the current web page environment to access the super Global variable you type dollar sign underscore server then you can access one of the key value pairs so for this demonstration I'm going to create a for each loop we're going to iterate over all of the pairs all of the key value pairs let's take our server as here Arrow value then I will Echo each key value pair key equals value then add a line break let's take a look all right we have a lot going on here here are the key value pairs found within my server super Global variable we're still beginners a lot of this is more for advanced PHP developers I more or less just want to raise awareness that this exists two keys that we're going to be interested in are PHP self and request method phpself is the location of this page the request method is either get or post the default is get if we have an HTML form that has the method set to post after clicking the submit button the request method would equal post let me demonstrate how we can use phpself I am going to create an HTML form let me get rid of this for each Loop the name of my PHP file is index.php the action attribute of my form is set to index.php any information that's posted will be sent to my PHP script however if I were to change the name of this file let's rename our file as home well our action attribute isn't going to be updated I'm going to navigate to our home page localhost.website slash home if I were to type in my name then press submit we're sending our form data to a file that doesn't exist it would be kind of nice if we could update this automatically that's where our server super Global variable can come in in place of a file name let's write a PHP script within the set of quotes we are going to access the server super Global variable at the Key of PHP underscore self this key contains the value of the current file path for this file save and reload everything you may need to navigate to our home page because right now it's set to index okay type in a username press submit and that should work then if we update the name of this file let's rename it to um start I guess that's all I could think of at the moment okay let's navigate to start .php type in a username press submit and that works just fine that's how we can use phpself to get the current file name however with phpself it is vulnerable to something called The cross-site Script we learned about cross-site scripts on the topic of Sanitation and validation if you do use phpself I do recommend enclosing this variable within a filter one that I recommend is HTML special chars so be sure to enclose that that'll avoid any cross-site scripts just be aware that this is something you might see in the future in your own studies at least you know what it is now the other key that we're going to talk about is request method request method is either get or post so if I were to reload everything but not submit anything the request method by default is get so another way to detect if a form is submitted is to access the request method normally we're used to saying if is set then access post then we access our submit button one problem with this is that at least in older web browsers you can submit a form without hitting the submit button there's ways around that a more reliable solution is to take a look at that request method within an if statement let's access our server super Global variable we will take a look at our request method and see if this is equal to post if it is then let's Echo I don't know hello type in a username it doesn't really matter I guess hit submit and we will display hello in the future I would prefer if we stuck with this way of handling post requests just because it's more reliable alright everybody so that's a basic introduction to the server super Global variable they're still way more advanced stuff involving it but I thought I'll at least give you an introduction just so that it doesn't freak you out in the future we'll have a little bit more practice with this when we create our own login form and well everybody that is the server super Global variable in PHP hello hello again everybody today I'm going to be explaining hashing in PHP hashing is the process of transforming sensitive data such as a password into letters numbers and or symbols via a mathematical process it's kind of similar to encryption but it's technically different basically speaking we can hide sensitive data from third parties like hackers in my example I have hashed my password pizza123 this is what my hashing algorithm spat out it appears to be what looks like a bunch of random letters numbers and symbols we might store this in a database then in case that database is compromised well then a third party wouldn't be able to see my original password this is what the third party would see in PHP to create a hash of let's say a password I'll create a password variable make up some password Pizza one two three I will create a hash variable then use the password hash function two arguments are a password then a hashing algorithm the second argument is technically a constant that specifies the algorithm the constant will set is password default if we set our algorithm to be password default and PHP currently we're using the bcrypt algorithm which is a very popular algorithm this hash is what we'll be storing within a database it's protected if I were to Echo my hash this would be the result our password is what is referred to as plain text we can plainly see what it is using the password verify function we can compare a password versus a hash if they're mathematically similar then that password verify function will return true let's write a if statement if password verify then we'll pass in a password and a hash let's say that we get some user input the user types in hamburger 666. then the other argument is going to be our hash just imagine that we're retrieving this hash from a database if our plain text password and our hash are mathematically consistent then this function will return true so let's Echo you are logged in else Echo incorrect password okay is hamburger 666 the same as our hash incorrect password what about hot dog one two one two that is also incorrect maybe pizza one two three oh look at that that's the right password you are logged in the password verify function will verify a plain text password versus a hash if there's a match we return true if not it returns false that's really what hashing is in layman's terms it's transforming sensitive data such as a password in two letters numbers and or symbols via a mathematical process and the purpose is to hide the original data from third parties and that is how to Hash a password in PHP hey welcome back everybody we have finally made it to the portion of the series where we will be connecting to a myosql database at this point in the series you will need to be familiar with mySQL queries I do have a full course on that on my Channel for free it's about three hours but yeah moving forward we will need to know MySQL there's two popular ways to connect to a mySQL database the first being the mysqli extension this is what we'll be using the other is PDO meaning PHP data objects many developers prefer PDO over mysqli because it can connect to more than just a mySQL database I believe you can connect up to 12 additional databases you know postgres being one of them however you would need to know object oriented programming which is an intermediate topic and we have not covered that yet as beginners we'll stick with the mysqli extension it's procedural alright well let's get started we'll need to create a mySQL database within our zamp server you'll need to open up the zamp control panel which is this thing make sure that these two modules Apache and MySQL are both started we will need to access phpmyadmin which you can do so by clicking on the admin button next to mySQL that should bring you to phpmyadmin otherwise you can just type in this web address localhost slash phpmyadmin phpmyadmin allows you to configure your database you can make SQL queries monitor the status export import data we'll be covering just some of the basics to create a database go to the databases tab we will create a database come up with a database name in the MySQL series we created a database named businessdb we'll stick with that but you can really name it anything then we will hit this create button we can create a table but we'll do that in a future topic let's be sure that that database is actually created let's click on our server go to databases yeah it's right here to drop a database you can check the database that you create then press the stop button but we don't want to do that but that's how there is some information we'll need about our MySQL server if you go to user accounts we will need some of this information such as the host name the username of root if there's a password for the server which there currently isn't and that's about it you can edit privileges too but that's outside of the scope of this topic all right we have now created our database so let's close out of phpmyadmin make sure that your MySQL server is running it currently is I'm going to create a separate PHP file just to manage our database connection so let's create a new file I will name this database.php anything related to connecting to our database we will handle within this PHP file this will be a PHP script we will declare a few variables the first will be DB underscore server this holds the name of the server for us that was localhost then DB user that was root a password DB underscore password I'll say just pass we do not have a password I will leave that empty then the name of the database DB underscore name I named my database business DB then we will declare a connection variable we'll shorten this to con meaning connection I will set that to be empty okay these are the variables that we'll need to establish a connection to the mySQL database we will take our connection variable set this equal to the MySQL I underscore connect function there are four arguments within this function the database server name username password and the name of the database let's add these variables as arguments so server user then password then database name let me make some more room I'll put these on a new line just for readability but there should be no change to its functionality if I do this if we establish a successful connection this variable is technically what is known as an object we haven't discussed object oriented programming it will represent our current connection one of a few ways in which we can check to see if our connection is up and running is we can use an if statement then place your connection within the if statement if a connection exists let's Echo you are connected else for testing purposes let's Echo could not connect I will save and reload everything then go to your database PHP file localhost slash website slash database dot PHP you are connected all right I'm going to stop the MySQL server then try and reconnect we get this ugly error message fatal error uncaught mice qli SQL exception for some reason if we can't connect to our database we don't want to display this error to the user we should use some exception handling we don't want to print any ugly error messages to the user they will have no idea what's going on I suggest when we attempt to create a connection we surround this code with the try block this has to do with the topic of exception handling we can try some code that might cause an error such as if we can't connect to our database let me just fix these we will try and make a connection if we encounter this exception I'll copy it we can take some other course of action after our try block let's add catch parentheses curly braces then add the name of that exception within the set of parentheses in place of displaying this error to the user let's Echo a message such as could not connect and I'll steal that here I'll get rid of the self statement so if we encounter this error again we will display could not connect that's a lot more obvious as to what's going on instead of that fatal error message if I were to start the MySQL server again then reload we are now connected this PHP file is now complete make sure to save everything we're going to close it I will head back to our index file let's generate some HTML after our PHP script in the body let's say hello doesn't really matter what you say let me zoom in a little bit since everything related to our database connection is handled within a separate PHP file we can include that within another file within a PHP script at the top of my index page I will use the include function we will include that file database.php to connect to our database so let's see if it works you are connected hello maybe I'll add a new line after could not connect I'll add a line break do that here as well much better technically it's not necessary to tell the user that they're connected to the database we were just more or less doing this for testing purposes one way or another though we should let the user know if there's any problems with the connection so we'll keep this for now if I were to stop the server reload we have that message that says could not connect all right everybody so that's how to connect to a MySQL server in PHP all right everybody so in today's video I'm going to explain how we can create a table using phpmyadmin there's two ways to get here you can either go to your zamp control panel then press this admin button next to mySQL or you can head to this URL to create a table let's go to our databases we should have a database already created in the last video we created a database named businessdb so let's click on it let's begin by creating a table name I'll create a table of users these will be registered users then set the number of columns I'll stick with four then we will hit the create button in this column we will set the name of each column our first column will be for user IDs let's name this column ID we will set the data type to be int we won't specify a length if you would like a default value you can set that here we're going to use the ID field to be set to Auto increment you can set the characters but we will keep that as the default like for some reason if you need I don't know Greek you can use Greek but let's just use the default to add an index you can do that here we will set our ID to be our primary index then I will click the Go Button to enable auto increment on a column you can check the AI button it's for auto increment that should be it for this column let's create a column for usernames the column name will be user for the data type let's say varchar then set a Max size I think 25 is good for our users let's have each user be unique then press go then let's move on to the next column this will be for passwords for the data type let's set that to be char which is right here I recommend hashing passwords in our database we won't be storing plain text passwords in case you know we get hacked or in case somebody uses SQL injection we'll be storing a hash of a password I'll set the size to be 255. encrypting and hashing algorithms are always changing and updating let's future proof our password field just by setting it to something large then let's add a registration date maybe we'll name the column register underscore date let's select not just date but date time I want to know the time that they register for the default let's use a current timestamp that should be good for our table if you would like some SQL code you can preview the SQL this is what we would be writing but we're going to be doing this automatically with phpmyadmin so let's save and we now have our table if I were to go to browse this is our table but there's currently no rows we'll be adding some rows with PHP but for testing purposes let's insert one manually using phpmyadmin so we will insert some test values with our ID it's set to Auto increment we don't necessarily need to put in a value for the user let's say the user is SpongeBob and for the password his password will be pineapple one you can also encrypt this password using password hash we'll cover hashing passwords in the next video with our registration date this is set to a current timestamp so that's going to be done automatically let's press go this would be the SQL query but yeah one row has been inserted let's go back to our table the username is SpongeBob password is pineapple1 and here is the registration date well date and time then to delete a row you can click this delete button then press ok and that is how to create a table in phpmyadmin and in the next topic we will be inserting some rows into our table using PHP hey everybody in today's video I'm going to show you how we can insert data into a MySQL table using PHP at this point in the series I am assuming that you have already established a connection to your mySQL database if you haven't here's some code that will do that in my index file I have included the code to connect my database at the end of my script I am going to close this connection just because I know for a fact I'm going to forget to mention that so I'm doing it now to close a connection you can type my sqli underscore close then pass in the connection our connection is underlined because vs code doesn't recognize it because we're including it from another file but it should work just fine now what we're going to do is write an SQL query I'll store that within a variable SQL this will hold our query So within quotes we can write some SQL query of your choosing we'll do a basic insert insert into the name of the database my databases users then list the columns I will insert a username and a password list the column user password then some values we're going to start with just some plain text my username will be SpongeBob for my password let's say SpongeBob's password is pineapple1 then to submit the query we can use the my sqli underscore query function then pass in our connection and our SQL query and that's it again vs code isn't going to recognize our connection because we're importing it if I were to run this query then refresh PHP in my admin we have our submission user ID of one it's set to Auto increment in this case the user is SpongeBob password pineapple and here's the registration date I set the registration date to be a current timestamp yes I am recording at two in the morning because I'm crazy let's say that for some reason we can't register a user maybe I forget a password well we get this fatal error fatal error uncaught mysqli exception we can surround our query with the try block we can try this code if there's any exceptions or errors that pop up we can handle them gracefully let's create a try block we will try some possibly dangerous code then handle any exceptions if they come up if this query is successful then let's Echo user is now registered if we encounter a problem let's catch that the exception we're catching is this one I'm going to copy it paste it then we will Echo could not register user oops gotta fix that all right let's try this again my query is not technically correct but we should be able to handle that exception could not register a user as you can see here with our SQL query let's insert some variables let's declare two let's declare a username username equals Squidward this time and a password equals clarinet 2. with our values within single quotes we will list our variables username and password let's see if this works user is now registered then if we head to phpmyadmin refresh this table we now have an entry for Squidward with the password of clarinet2 art passwords are plain text it would be much better if we were to store a hash of a password just because you know these are plain text it's not secure so let's hash our password we'll create a hash equals we will use the password hash function the two arguments are the password and an option for an algorithm we will use the default password default technically we're using the bcrypt algorithm that's the default currently we will insert our username and our hash in place of our password let's change the username though let's assign Patrick his password will be rock3 let's see if this works okay refresh phpmyadmin and there is Patrick user ID3 username is Patrick here's the hash of the password and the registration date all right everybody so that's how to insert data into a MySQL table using PHP hey everybody in today's video I'm going to show you how we can retrieve data from a mySQL database using PHP I have already established a MySQL connection I'm going to include that file that establishes the connection then at the end of my script I will close that connection with the MySQL close function the first thing we'll do is write an SQL query I will store that within a variable named SQL in my table I would like to select a user let's select SpongeBob the query would look something like this let's select let's say everything from our table which I named users where if you don't write a where Clause your query is going to return more than one row I'll show you how we can handle that later select all from users where user is equal to SpongeBob but put that within single quotes this is our SQL query to make a query we can use the my sqli query function we will pass in our connection object then our query SQL if successful this function will return an object we will store that as a variable named result so result is technically an object somewhere within this object there's an associative array to find how many rows are returned from our query function we can place that within an if statement we will use this function mysqli underscore num rows function this function will return how many rows are within our result really it should only be one in this example if there's at least one result we could write a condition such as if the number of rows is greater than zero there's at least one matching row to get that Row from our result let's store that within a variable named row set this equal to the my sqli underscore fetch underscore Asos for associative then pass in our result this function Returns the next available row within our object our row is an associative array we can access this data by a key then be returned one of the values let's Echo row at index of ID then I'll add a break afterwards let's see what we have we have the user ID of one let's get the username I think it's just user one SpongeBob then the registration date reg date so these are the names of the columns yeah here's SpongeBob's ID is username and the registration date those were the fields found within our table now if there are no results let's say we're looking for Sandy well we don't do anything let's add an else clause else let's Echo no results found or maybe no user found no user found that's how to retrieve one row from a table what if you need to retrieve multiple rows we can make some adjustments we would want to utilize a loop I'll enclose this line of code within a while loop while there are rows we will display each user's information let's get rid of the where Clause we will return every user you would just need a looping structure of some sort to Loop through each row within your result alright everybody so that's how to query data from a database you write an SQL query you use the query function this returns an object then you'll need to get each row from the object and then you can do that with this function if you need to return more than one row you can stick that within a loop like a while loop and that is how to query data from a mySQL database in PHP hey everybody in today's video we're going to create a registration form in PHP so sit back relax and enjoy the show a few prerequisites that we'll need for this project is that we'll need a table within a database we have created one in Prior topics we have an ID a user a password and a registration date you'll need a working database connection as well which is what we have done here in my index file I have included that PHP code that contains my connection then we will write a second PHP script within this file we are going to close our MySQL connection because if we don't do it now I know that I'm going to forget later so let's close it now and we are closing our connection let's go to our index file generate some HTML we'll create a pair of form tags for the action we're going to set this to a PHP script within quotes just in case I update the name of this file this script will reflect the changes so let's create a PHP script we will get from our server super Global variable phpself accessing the key of PHP self that will give us the name of the file but this is vulnerable to cross-site scripts we should enclose this within a filter HTML special chars is a good one for this situation then we should set the method equal to post because we're creating a registration form let's add a title to our web page let's use an H2 header tag welcome to fake book it's like Facebook but worse we'll have a user type in a username and a password username add a break add a text box input type equals text the name attribute will be username add a break and I'm just saving and reloading everything as I go along we'll need a password create an input tag set the type equal to password the name will be password as well add a break then let's create a submit button that is also an input tag the type will be submit for the name let's set that to be submit as well then for the value maybe register that looks pretty good okay our form is complete let's go to our PHP script the method of our form is set to post we can detect that with an if statement we will access the server super Global variable and check the request method key so type request method is this equal to post has the request method changed to post if a post request is made we should filter both the username and the password it just in case they contain a malicious script so let's assign our username equal to we will filter the input using the filter input function type input post because we're using post the second argument is the attribute name username then a filter type filter sanitize special chars let's copy this line then paste it directly underneath but change username to password do that here too so that should filter any malicious grips once we have a username and a password that's been filtered we'll check if one of these fields is empty we can use an if statement let's check if our username is empty if empty function our username then we will Echo please enter a username else if our password is empty empty function let's check our password please enter a password Let's test that real quick I'll type in a username but not a password please enter a password I won't type in a username but I'll type in a password please enter a username if we type in both nothing happens but that's good if our username isn't missing and our password isn't missing we can execute and else clause in our database we'll want to store a hash of a password let's take our password declare a hash variable then use the password hash function we will pass in our password then an option let's use password default okay now that we have our hash we need to write an SQL query we'll insert the username and the hash of the password we'll store our SQL query within a variable SQL then we will write the query it's going to be an insert statement insert into the name of the table in this case my table is named users list the columns user and password values list the values we will be inserting our username variable as well as our hash the hash variable then to initiate the query we can use the query function mysqli underscore query pass in our connection as the first argument followed by our SQL query once that's complete we should probably let the user know that they registered successfully let's Echo you are now registered for the username I will type SpongeBob will have a password of pineapple one I'll click register you are now registered let's go to our table refresh I might need to zoom out a little bit and here's the first record user ID one username is SpongeBob this is the hash of the password and I have a registration date one important thing I forgot to mention I'm only allowing in this table unique user IDs if I were to register another user as SpongeBob we might have a little problem SpongeBob I'll make up another password fry cook2 well we get a fatal error uncaught MySQL exception we have a duplicate entry for SpongeBob we never really talked much about exception handling but one way in which you could handle this exception is that we can copy the exception name place any code that might cause an exception within a try block then catch that exception in this case it was a MySQL exception then let's Echo that username is taken there's still a lot more you can do with exceptions but that's more of an intermediate topic I would say let's type in SpongeBob again brycook 2 and register that username is taken let's create the username Squidward Squidward will have a password of clarinet 2. you are now registered and here's Squidward all right everybody so I thought that would be a fun final project for us to do to wrap up this video I would look at both object oriented programming and exception handling next hey if you made it this far be sure you've smashed that like button leave a random comment down below and subscribe if you'd like to become a fellow bro
Info
Channel: Bro Code
Views: 343,067
Rating: undefined out of 5
Keywords: php, php tutorial, php tutorial for beginners, php course, learn php, php for beginners, intro to php, php programming, php project tutorial, web development, free php course, php course online
Id: zZ6vybT1HQs
Channel Id: undefined
Length: 240min 0sec (14400 seconds)
Published: Wed Mar 29 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.