PHP REST API From Scratch [1] - Database & Read

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hey what's going on guys so I recently had a couple people asked me why I stopped doing PHP videos on my channel and I definitely have not I just tend to focus more on front and back-end JavaScript because that's really my personal first choice when it comes to web development mostly because of the full stack capabilities and I really love JavaScript but I also do love PHP it was actually the first language I ever learned I think it's very practical it's it's it's easy for beginners it's still very relevant a ton of websites and applications use PHP so I woke up yesterday and I you know I read some of those comments and I decided that I would do a little series and create something with just PHP no framework no laravel no Symphony just pure PHP code and we're gonna create a REST API okay now when you create a REST API with a framework like laravel it's pretty easy a lot of it is automated a lot of it you're not really you're not really seeing what's going on it's very abstract but we're just going to get into it and just coat it out with straight you know blank text editor start from a blank text editor so it will take longer than using a framework or something or library or whatever but you know I think that ultimately if he if you're interested in PHP it's going to help you learn more of the language and we're gonna use object-oriented concepts you know we'll have a database class and we'll have some models that will we'll use that database class with our database objects and we'll also use P do which is PHP data objects which has to do with connecting to our MySQL database now I'm not going to go into like the concepts of a REST API or PDO I have other videos explaining that stuff I have a PDO crash course I have a video called what is a REST API I have a 20 video series on YouTube called PHP front to back that shows you all the basics so the are some I guess prerequisites to to this this series if if you're interested in you really don't think you're ready for something like this not that this is super advanced but it's it's definitely not like beginner based and I'm not gonna explain every little thing like what is what a function does and all that stuff all right so let's get into it I'm already talking too much I'm using postman for my my HTTP client basically to connect to my API and make post requests get requests and all that stuff so I would suggest downloading that from get postman com unless you use something else if you if you want to you know get really technical and use something like curl or some command line tool I know vs code also has some rest client extensions so whatever you want to use but I would suggest postman it's really easy and then for my environment I'm just using xampp which is just a suite that includes apache maria DB which basically is MySQL and PHP it also has PHP myadmin which we'll use to import our database okay so to get started we of course need some data so I'm gonna go to PHP myadmin which if you're using xampp it's already included if you're using like I don't know vagrant or docker or something you can get that installed or you can just use the the SQL shell whatever you want to use to import this now what you want to do is go to the github repository that's in the description and you'll see a file in there just you know you can clone that repository or download it and there's a file called my blog dot SQL and we're just going to import that into a new database instead of creating everything manually so I'm going to create a database called my blog and then I'm gonna go to import choose file and I'm just gonna grab that SQL file and click go and then if we look at our structure here you'll see we have a post table and a categories table and just to show you real quick just in case you are you are creating this stuff manually the structure we have an ID in our posts which is the primary key auto increment category ID which is gonna represent the whatever category this post is title body author and created at which is a date/time field and it's the current timestamp so this will automatically get filled we're not gonna have to actually add this in our query and then we have some data so just some posts with some category IDs a body author created that and then if we look at our categories table and we look at the structure it is just an ID which is the primary key the name and it created at which again is the current timestamp and then if we look at the data here we just have a couple different categories okay just the name and create it at so that's our data structure that will be working with it's very very simple so now we can get started with our code what I'm gonna do is open up my htdocs folder okay so since i'm using xampp htdocs is basically my server root i'm gonna create a new folder here and I'm gonna call this P PHP underscore rest underscore my blog which I already have there so I have to actually delete that and say PHP my blog rest no PHP rest my blog you can call it whatever you want but this is what I'll have it in github as so I'm going to open this with my text editor I'm using PS code which I highly recommend but of course you can use whatever you want now as far as our file structure we basically have three different parts we're gonna have our config folder that's going to hold our database class which is going to be used to do our core connection to MySQL using PDO then we're going to have a models folder that will have our post post model and category model and then we're gonna have our front end facing API folder where that'll have the files that we actually hit in the HTTP client in postman alright so those will be the three basic parts of this of this project so let's create a folder called config we want to start by creating our database class so we'll create a file here I'm going to call database dot PHP and I give it a capital D because it is going to be a class and whenever I create class files I like to you know give it an uppercase at the beginning so let's put in our PHP tag and create a class called database so this class is going to have some properties which are basically going to be our database parameters to connect so these are going to be private meaning they can only be accessed in this class so we'll have a host which is gonna be localhost we're gonna have a database name so I'll say DB underscore name which I called my blog we're gonna have our user name this is your database username which I'm using my root user and then you want your database or your your root users password or or whatever user you're using which in my case is just one through six and then finally we want a property called Co n n this is going to represent our connection all right so next thing we want to do is create a method to connect say DB connect and let's give this this will be public function and we'll call it connect and then first thing I'll do is just set the connection property to know all right now whenever you want to access any of these properties and this is just basic object-oriented principles in PHP you want to use this and then the arrow okay so we're pertaining to this with this property here or attribute we're just setting it to null and then we want to we want to basically connect through PDO meaning we want to create a new PDO object and pass in the stuff we need so I'm going to actually put this in a try-catch block all right so we're going to say try catch and inside catch we're going to put a parameter here it's going to be PDO exception which will be a variable you could call it you could call this anything we're gonna call it e and then in the catch basically if something goes wrong if there's an error we're just going to echo connection error and let's concatenate on and we can take that exception variable and it has a method called get message which will tell us exactly what's going on if it doesn't connect okay now in the try is where we actually want to connect so we're going to say this con and we want to set that to a new PDO object and this takes in a couple things it takes in what's called the DSN which is basically your database type and your host it also takes in your database name username password all this thing all the things that are needed to connect so we want to put some quotes in here and we're saying MySQL because you can use other types of databases with PDO and then colon host equals and now the host that we're using is going to be this property right here so since that's a variable we need to concatenate so we're going to put a dot like that and say this post then will concatenate back to a string put a semicolon and then we want the DB name which will equal and then we want to concatenate this DB underscore name back to a string put a semicolon actually we don't need a semicolon because or this because this is actually the last parameter or the the last of this first parameter of the DSN now we want the username as a second parameter so this username and then the password is the last one so this password okay and just double check your concatenation here this stuff used to confuse the hell out of me when I was when I was starting out with PHP welljust yeah that's fine all right so now that we've done that the next thing or the last thing I want to do here is just set the error mode I want to be able to get exceptions when we make queries in case something goes wrong and it'll tell us what's going on so we're gonna say this connection or con and then set to attribute what is that so set attribute and here we want to say PDO double colon attr so attribute underscore and then error mode eerr mode and then comma and then we just want to put PDO error mode underscore exception and that's it and that PDO has a lot of different attributes that you can set if you want to look at the documentation or if you want to watch my crash course and or whatever and oh and we also need to return the connection so under the try-catch we're just going to return this con and that's it that's our database class and that's what we'll use in our in our model so let's save this and that's it we can close that up so next thing we're going to do is create another folder called models this should not be in the config didn't mean to do that okay so in models let's create a new file called post.php and this is going to be a class so just like we did with database we're gonna say class and we're gonna call it post and we want to do some DB stuff here so we want a private property of co NN representing our connection and then we want our table for this model which is going to be posts alright then we'll set our properties I mean they're all properties but these are I guess our post properties so like the ID and I'm gonna set these to public so ID we're not going to set them to any value or just basically initializing them so let's say public category underscore ID public now here I'm saying category name and you might be saying well we don't have a category name field in our database we're actually going to use a join in our queries so that we can kind of combine the tables together and we can get the category name of the post ok we also want a title we also want the body author and what else created at ok so that should be all the fields that we want now we want to create a constructor all right now a constructor we're gonna say with Divi a constructor is basically just a method a method is a function within a class and a constructor is a method that runs automatically when you instantiate the class or when you instantiate an object from a class and to create this we're gonna say public function and then double underscore construct ok that's how you create a constructor and then when we instantiate a new post we're gonna pass in a database object so we're going to say DB right here and then all we want to do is set the connection of this class to that DB okay just like that all right so now what we're gonna do is go below the constructor and we're going to create a method to get post or read posts so we're going to say public function we'll call it read and in here what we want to do first is create our query okay so we'll create a variable called query and we're gonna set it to select let's do select now I'm going to use some aliases here and we're gonna do a join because we need to get that category name I want that as output when we when we look at our posts so we're gonna say C dot name as category underscore name I'm actually going to separate this a little bit to kind of make it a little more readable so we'll go like that so we want it to select C dot name as category name and put a comma here oops and then underneath that we want to get from the post table we want the ID I'm gonna say PID we're using P as an alias it doesn't know what P or C is yet but I'll show you where we actually define that we also want the category ID okay we want the title we want the body author and created at alright so we want those from the post table so we want to go right here I'm gonna go back one and say from and then we want the name of the table now we know it's the post table but we actually defined it the table as a property up here so we want to put that so we need to actually put some quotes here and then concatenate since it's a variable and say this table like that so we're saying from whatever the table is and then this is where we can just put a P and we're basically assigning posts as P so up here when we say PID it knows we mean the post table now below that I'm gonna do a left join and this is probably the most complicated query of this whole thing now a join is when you bring in another table so we want to bring in categories as C okay so this is where we define C as categories and we wanted to we want to bring it in on where P category ID is equal to C dot ID okay so we're making a correlation here between the category ID field and in the post table and the ID field in the category table so that's how we're gonna be able to get this category name okay because categories does have a name field but we're saying get it as category name and then the very last thing we want to do in our query is just order so we're gonna say order by and let's order by the post table created at field and we'll say descending alright I'll just put this quote up here okay now if I just if I just had created that it would get confused because both well actually we didn't select it from the category table but both of them do have a created at field so it's good to have these aliases so that's our our query I realize it is a little advanced if you're not if you've never done joins or anything if you watch my PHP front to back course we do go into joins and stuff like that and I do also have an SQL crash course which is about an hour long I try to try to cover most of the technologies you know web development stuff so we want to put a semicolon there and then next thing we want to do after we create our query is create our prepared statement okay so we're gonna create a variable the convention is STM t for statement and then we're going to take our connection so this con and we want to call the preparer okay so this is PDO right here so we want to prepare our query okay once we have that statement we're just preparing it we haven't executed it yet so that's what we want to do next is we want to execute the query and we can do that by saying s TM T and it has a method called execute and then the last thing we want to do here is just return our statement all right so that is our read method hopefully I didn't make any mistakes so we'll just save that now I don't want to end this video yet because I want us to actually have have some kind of result so I want to be able to at least make a get request and get our data so now we're going to create our API folder which is like kind of like just our front facing API that we're gonna be able to access and let's create a folder in here called post so anything to do woops anything to do with posts will go in here so I'm going to create a file called read dot PHP so this file here we're going to interact with with the model so let's start off here of course we need our PHP tags and since this is going to be a REST API that we're going to access through HTTP we need to add a couple headers so in PHP we have the header function we can use and I'm going to add the access - control - allow - origin and since this is a completely public API and we're just going to put an asterisk err okay so this should be able to be accessed by anybody we're not getting into authorization or tokens or anything like that that's way beyond this what we're doing here and then I also just want to add the header value of content type and we want to say that this we want to accept Jason which the mime type or whatever is application slash Jason alright and then we need to bring in we're gonna say include once we need to bring in the database which is it's up to directory so dot dot slash dot slash and then it's in the config folder and then database dot PHP and actually I'll just copy that down then we also want to bring in models and we want to bring in our posts model alright so now that we have that let's go ahead and in Stan she ate our database object instantiate database and we also want to connect to it so for that will create a variable called database set it to a new database object and then we'll create a variable for UNK for our basically our connection and we'll set that to database connect ok and that connect is is the one that we created so if we look at our database class we have our connect it's going to do all this stuff alright so now that we've done that let's instantiate our post object a blog post object so we don't get confused with like a post request and say post equals new post now remember when we created our constructor in the post it takes in this DB and then it adds it to the connection so that we can go and we can do our stuff down here with our query so we need to pass in that DB object like that all right now once we do that we want to basically call our read method okay this right here our read function inside the the post class so let's say blog post query and we can say let's create a variable we'll just call it result and we'll set it to post read and then I also want to get the row count so right here I'm going to say get row count and we can do that let's create a variable just call it num and we'll set that to our result and then it has a method called row count like that so we want to basically check to see if there's any posts so let's say check if any posts so we can just check that number so we'll say if num is greater than 0 that means there's posts we're gonna have an else here as well so if there's posts first thing we're gonna do is initialize an array so I'm gonna say posts underscore arr and just set it to array so just a blank array and then the way that I want to structure this is when we make a request I don't want I don't want it to just return a JSON array with the data I wanted to have a date of value inside and then have it just in case you want to add other stuff other than the data like pagination stuff or I don't know maybe just like like a version info anything like that so I'm also going to do this I'm gonna say posts or pote yeah posts array so I'm going to take that post array we just created and then we're gonna say data and set that also to an array and that's where the actual data is gonna go so now this result yeah this result is going to give us you know the result from the read function that we created so we want to loop through that so to do that we'll create a while loop and inside here we're gonna say while and then we're gonna have a variable called row and set that to result fetch and then remember we're using PDO and we can fetch it as different things I want to fetch it as an associative array so we're gonna say PDO double underscore fetch underscore a so she and you can watch my PDO crash course to learn more about what we can get and stuff like that now this row variable we will be able to access the data like if we want the title we could say row title like that but I don't want to do that what I want to do is I want to extract this whatever this is and have that as a variable so what we can do is we can use extract and then pass in row and now we'll be able to act we'll be able to use like title and body and stuff like that instead of that that row title row body all right now we want to create a post item for each post so I'm going to say post item equals an array and inside here I'm gonna say let's say ID just gonna be ID title body now the body usually in a blog the body is is allowed to have HTML so what I'm going to do is I'm going to wrap this in a function a PHP function called HTML entity decode and then pass in body like that alright and then also author and category ID and also category name remember that our query will also give us that alright so now the next thing we want to do is take this right here the data value in the post array and we want to basically push to that so under the post item let's say push I will say push to and we want to push to the data so we'll say array underscore push which is just a PHP method to do just that and we want to take the posts underscore array and then the data value and then we've what we want to push onto it is the this post item okay and it's going to loop through each post and do this for each one now we want to go outside of the loop which ends right here and we want to turn it to Jason because right now it's just a PHP array and we don't want that we want to turn this to Jason and we want to output so for that we'll say echo and then we have a function called jason in code and we want to pass in our posts all right okay and that should do it and then else meaning that if num is zero meaning if there's no post what do we want to do we want to just echo out just put a comment here or no posts well echo out Jason and code and we'll just put an array in here and say message and we'll set that to no pose found all right so that should do it let's save this and now we should be able to do this we should be able to test it out so let's go to postman and we're gonna make a get request to HTTP localhost / what the hell did I call this PHP rests my blog slash and then API slash and you could if you want you can map this to a host using your host file if you don't want to use like localhost / something you could map it to a local domain but I'm not gonna go through that API slash post slash read dot PHP okay make sure it's a get request and let's click send and there we go so as you can see here we have a JSON object which has a value of data and that value or our key of data I should say and that value is an array of our posts okay and if you look at each one we have the ID we have the title of the post we have the body which is just some dummy dummy text we have the author the category ID and we also have the category name okay and remember that category name is not an actual field in our post table we did a join with the categories table and that's how we got that all right so I think that this is a good place to stop guys in the next video I want to do two things hopefully depending on how long it is I want to be able to to get a single post because right now we're getting all of them I want to be able to get a single post and I also want to be able to create a post so we'll have to make instead of a get will make a post request so what that means is that we'll have to add to our post model so we're gonna add a read single and a create method and then we'll have to also create those files to hit with our with our client alright so that's it hopefully you enjoyed this and I hope to see you in the next video
Info
Channel: Traversy Media
Views: 348,202
Rating: 4.9304147 out of 5
Keywords: php, php rest, php rest api, php oop, php pdo, rest api, php restful api
Id: OEWXbpUMODk
Channel Id: undefined
Length: 32min 17sec (1937 seconds)
Published: Sun May 27 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.