PHP REST API From Scratch [2] – Single & Create

alright guys welcome to part 2 of creating a REST API with just pure PHP no frameworks or anything in the last video we set up our core structure we

set up our database class we set up our post model and we created the read function and then we created our read dot PHP file to basically use the model to query the database and get the data

and then they were seeing the result here in postman what I want to do now is create I want to be able to get single posts so we want to be able to hit like read single dot PHP and then add a query

parameter of ID equals set let's say 3 and get just just the posts with the ID of 3 okay just that object so let's go back to vs code and we want to be in our post model so models post dot PHP and

we're gonna go right under the read function or method we created make sure you're still within the class and let's say get single post so let's do public function single post

are not single post let's say read single since the first one was called read and then the query is gonna be pretty similar so what I'm gonna do is I'm going to just copy all this we want

us to type it out again and it'll paste that in so the Select is gonna be the same we want to get the same stuff it's from the same table we want to use P and C as our alias we're doing the left join

we don't need to do order by because we're just getting a single post but we do need to specify what post we want so we're gonna say we're PID equals question mark all right now this

question mark I'm using because we're going to use P do z' bind per a more basically going to bind something to this later on it so it's basically a placeholder and we want what we're gonna

bind is the ID and then let's just say limit 0 1 so we just want to get one record oops why isn't this this isn't formatted right and we just bring these back all right so that's fine all right

so now underneath actually we need a quote here and then X semicolon so underneath this okay make sure you're in your read single function still allow actually let's tab this over so while

we're still in the read single we want to now prepare our statement and this will actually be the same as what we did up here so we can actually copy it so I'll paste that in now we want to bind

the ID to this right here because right now it's just a question mark so to do that we can say statement bind / Ram and we want the basically this is a positional parameter in P do you can

have positional parameters or named parameters and we will be using named parameters for like our inserts and stuff but basically we could have more than one of these but there's only one

so we want to say the first parameter should be should bind to this ID whatever that's going to be okay so we bind the ID then we execute the query just like we did up here so I'll just

grab this so I'll say execute query and then instead of just dumping out the statement like we did with the root with the read we want to fetch the array here that's going to be returned from this

query which will be one single record and then we want to assign the properties to whatever comes back all right so let's say Rho equals and then we want to take that's the statement and

we can call fetch on that and we want to fetch an associative array so PDO double underscore fetch underscore soch and then we want to set the properties to whatever is returned so we want for

instance this title to equal row title all right and I'll just copy these down we'll do two three four five and then what I'll do is highlight this title here and do control D that'll take the

next one and we'll say body all right we'll do the same thing here so this will be author so title body author we also want category ID and we also want category name

okay and that should do it as far as this read single method goes so we'll save this and now we're gonna go to our post our API post folder and create a new file called read underscore single

dot PHP alright now again this is gonna have a lot of the same stuff that are read dot PHP had so I'm gonna copy from here we want the headers we want to include this stuff we want to

instantiate our database our post and yeah let's just grab that just to save some time I don't want to type in the same crap over and over then once we do that we need to get the ID from the URL

so let's say post we'll set the ID and we want to do a conditional here what I'm going to use the ternary operator so it's like a shorthand if and we also want to use is set okay is set we'll

check to see if a parameter if something is set now we want to use this money sign get super global again if you watch my PHP front-to-back you'll learn all about the post and getting on the

superglobals and stuff like that this is basically how we get from a parameter if it's like something dot-com and then question mark ID equals three this get ID this is how we can get this value

right here okay so that's what that's doing so we're gonna say if that's set then okay question mark were using the ternary operator then you just want to say get ID we want to set it to that

else so we use a colon for else then we just want to call the Die function which basically just cuts everything off and and nothing will display or happen so it'll look for the get ID if it's there

it'll get put into the post ID now once we do that we want to call the read single meth that's in the post model that we just created so this right here this reads

single so let's say get post and I'll say post read underscore single all right now once we do that remember we need to return JSON data so we're going to create an array so we'll say post

single post array is going to be equal to array and then we just want to do ID will be equal to whatever whatever the post ideas title post title we want to what else body will be post body author

and category ID and we also have category name okay so now we have our post array last thing we need to do is is convert this to JSON data so let's say make Jason and we're

gonna use print our print underscore R which just basically prints an array but we want to wrap this array so we'll have the post array but we want to wrap it in jason underscore in code okay so

hopefully that works let's save it let's go to postman and let's let's actually believe what we did here so it's going to be read underscore single dot PHP with the idea of three we'll send and

there it is so we just have a single object with all that data and if we do like one we'll send and we get the post with one okay so now let's move on to where are we here do that let's move on

to creating a post okay so this will be a little different it'll be a post request that we make from our API but let's close up everything except the model will go under the read single that

we just created and let's say create post okay so it'll be public function create and let's see we want to first of all create our query so let's say query now

this is gonna be an insert so we're gonna say insert into make sure you put a space here and then we want the table name so we want to concatenate this table and then concatenate again and

we'll go down here and we'll say set title and then this is what we're going to use named parameters in in PDO so we want to do : title like that alright and we'll define

these later so title body is gonna equal colon body author is gonna equal call an author and category ID category ID and let's see this should actually end with a quote

and like that alright so that looks good we could actually put this on a different line if we want yeah that's fine whatever so that's our query now we want to prepare our statement so make

sure you're still in the create we're gonna go directly under the query so prepare statement is going to equal this connection prepare pass in our query just like we did with the Select now

what we want to do is we want to actually clean up our data because this is going to be data that people are submitting so we're gonna wrap these and we're basically going to take the data

and wrap them in a couple security functions so let's say this title and we want to set it to this title but we want to wrap this in a couple functions one is going to be HTML

special chars because we don't want any special we don't want any HTML here or any whatever HTML special characters and then we also want to strip any tags okay so we'll say strip underscore tags

wrap that okay so we're just running this the title through strip tags and through HTML special chars and there's other way too there's other ways to sanitize your data this may not even be

the best way there's there's so many and people argue over it all the time but I'm not really gonna get into like super security and stuff like that so for what we're doing here this is fine now we're

gonna do this for c2 3 for more field so we're gonna add body and let's dude author and category ID okay so clean the data now we need to bind the data okay what I mean is is take care of this

stuff this colon title colon body so we're binding named parameters here so St MT just like we did before we're gonna do bind parameter which let's say title and we're gonna bind it to

whatever this title is alright so we'll copy this down three more times and let's see this here is gonna be body again I'm just I'm selecting this and ctrl D once to get the next one here so

I don't have to type it twice author and category underscore ID so that'll bind everything then we need to execute our query so for this we're just gonna say if statement now remember we're not

returning data here we're creating data so I'm just gonna do an if statement so if statement execute so basically if it executes and everything goes okay we just want to return true now if it

doesn't we want to return false but if it doesn't I want some extra data so this is where remember we set the arrow mode to arrow mode exception so we'll be able to print say prints error if

something goes wrong so what I'm going to do is use a print F and we're gonna say error and then put a percent s which is basically like a placeholder we'll put a new line so we'll concatenate /n

and then we want to put our state our error which we can get from s TM t error like that alright so if something goes wrong without query it we should be able to see it in the raw tab in in postman

so that's it let's save that and now we can go when we can go to our API post folder create a file called create dot PHP and here let's see we're gonna do a lot of the same stuff so that we did in

the other two so from read I'm gonna just copy yeah we'll copy this stuff and go to create and we want to we want to add a couple additional header values here

since it's a it's going to be a post request so I'm actually going to copy that down so we want to put what methods we want to allow here which is going to be just a post request so I'm

going to say access control allow methods and the value for this the value is going to be post all right and then I'm also going to put here the actual allowed header values so let's allow

about allow access control allow headers and then it's it's basically which what are we allowing as far as these okay so this is actually one of them or I'm sorry this is actually one of them allow

headers so we're going to grab that and this is going to just be a comma separated list so let's paste that in we also want let's see the content type and the allowed methods and then I'm

also going to allow authorization even though we're not using it I still want it to be allowed and then also we want this X – requested width which will help with cross-site scripting attacks and it

also has to do with cores and in it stuff that I really don't want to get into but I'm just going to put it here anyways in case we do something else with this later

in case we build a front-end or something so that should be it for the headers I believe hopefully and then we're gonna go down here after where we instantiate our blog post object and we

need to get the data that's posted so when we when we make our requests from postman we're going to add the title the the body the author and the category ID and we need to get that so we need to

say get the raw posted data and there's a few ways to do that what we're going to do is we're gonna say Jason decode because it's going to be in JSON format and then we can say file get contents

and then we're gonna pass in here PHP : double forward slash input and that should get us whatever is submitted okay so once we do that let's assign what we have in the data to the post so

to the post model or post object I should say so post title will then equal data title okay and we'll just copy this down three more times and we're also going to get the body we're gonna get

the author and we're gonna get the categoryid okay so now we want to actually create the post so we're going to use the method that we created in the model but I'm

going to put it inside an if statement just in case it doesn't happen then we can say whatever post not created so let's say post and then we'll call create which we just created and then if

that happens then let's echo Jason underscore and code because we want to echo Jason content and we're gonna pass in here array and this array will just say message as the key and as the value

will say post created okay else then let's just echo out post not created so when you're dealing with PHP I mean it's it's a little tougher than JavaScript because you have to actually

encode your arrays as Jason where with JavaScript jason is basically a JavaScript object so it's it's much easier to to deal with okay there's less there's less I guess conversion so let's

save that make sure everything is saved okay wait a minute what's going on here what did I do if else oh I don't I didn't close this else did I wait a min what the hell

okay what am I missing here oh wait I don't thinking we're in the class still there we go sorry about that I could cut that out but I don't want to so let's try this out we're gonna try to create a

post through postman so we want to go to post slash create dot php' and we're going to change this to make sure you change it to a post request and we want to go to headers and we want to specify

the content type so if we start to type content we'll get this drop down we want content type we want application slash Jason okay remember in the header that's

that's what what we accept that's what our API accepts and then the body I'm gonna choose raw because I'm just gonna submit raw Jason all right so we want to put double quotes around both the keys

and the values so let's do title and let's just call this my tech post and for the body I'll just say this is a sample post I also want and then we want categoryid

which one I believe is technology all right so let's try this out well send we get post created that's a good sign now we could we could check this a few ways we could just make another get

request to post read dot PHP that'll that'll give us all of our posts and there it is my tech post and the reason it has an ID of seven is because the last one was six

and the ID is auto increment so I mean another thing we could do is check check our database itself which should be there I mean if it's in there yeah right here my tech post ID 7 category ID

sample post got the author of the created at so there we go we successfully have added a post through our API alright guys so I think that this is a good place to stop in the next

video what I want to do is start to work on being able to update posts and also being able to delete them

In this part of the series we will add functionality to fetch single posts as well as make a POST request to add posts


💖 Become a Patron: Show support & get perks!

Website & Udemy Courses

Follow Traversy Media:

    php php api php oop php pdo php rest php rest api php restful api rest api