Writing Basic SELECT Queries0:00
Alright, welcome back. We have a lot to cover in this video, so no intro this time. Let's just dive right in. I will open TablePlus, access our database, and yeah, in the last video, we created this POST table. But of course, the end goal is to figure out how to query this table from our php. And query is sort of the key word. To do that, we need to write an SQL, or SQL, query. We'll do our first one together. SELECT * FROM POST.
We'll do our first one together. SELECT * from POST. And I can run that, or you can see, I can press Command-Return on the Mac. Okay, and sure enough, here's the results. All of the records from the POST table. So let's break this down. SELECT is a key word. It's obvious. What do you want? Give me this.
What do you want? Give me this. But what is star? Well, that means everything. But I could change it. I could say, well, give me only the ID column, or the title column. Let's try it out. Select ID from Post. Now you can see, I get all of the records from the Post table, but only the ID for each one.
Now you can see, I get all of the records from the posts table, but only the ID for each one. Or I could say, give me only the title. Or I could use a comma-separated list. Select ID, title from posts table. Or in this case, because that's all I have, it's functionally equivalent to select *. Now I could also add a WHERE clause. Maybe I only want this blog post here. OK, well, let's use that primary key, or the unique identifier. Select * from posts WHERE ID = 1.
Switching to PHP PDO1:26
OK, well, let's use that primary key, or the unique identifier. Select * from Post, WHERE the id equals 1. And now I get that single result, or 2. Pretty cool, and more importantly, pretty easy to write, which I like. All right, let's now switch to my editor. Now, of course, later we will organize and refactor our code. But yeah, when you're first learning, it's totally fine to dump and throw everything within index.php. All right, so we need to connect to our MySQL database. And to do that, we're going to use something known as PDO, or PHP Data Objects.
All right, so we need to connect to our MySQL database. And to do that, we're going to use something known as PDO, or PHP Data Objects. I'll warn you, this can be a little confusing. And honestly, in real life, we're working developers, you don't write this sort of code too much, because it's already been done for you when you use libraries and frameworks. But nonetheless, it's important to at least figure out the basics. And then later, you can use what's known as libraries or abstractions. Okay, so the first step is to initialize PDO. To do this, we need to create a new instance of the PDO class. Sounds very programmery and very confusing.
Classes and Objects Primer2:29
To do this, we need to create a new instance of the PDO class. Sounds very programmery and very confusing. And even worse, the idea of classes and objects and instances are entirely new to us. We haven't yet reviewed it. So here's what I'll do. I will give you the 60-second rapid-fire version so you understand it. And then I promise, later, we will cover it in great detail. Okay, so we can define a class like so. And you can almost think of a class as a blueprint for anything. Now initially, we often say, look for the nouns.
to the outside world. But yeah, for now, just come along for the ride, and we'll explain it more in the future. And I never want to do something like this, because then, think about it. I'm now saying the blueprint of a person is that all people have a name of Jeffrey. And of course, that's not true. So I will simply define it like so. What else? A Person has an age. And then a Person has behavior, like breathe. So I could define a function called breathe, just like you're used to.
And then a person has behavior, like breathe. So I could define a function called breathe, just like you're used to. But notice how for this function, or actually functions within a class, are called methods, which can be a little confusing, but they're still functions. Anyways, notice there's no visibility before function. So do we have to do this? And the answer is, well, yes and no. No, you don't have to do it, because technically, the default visibility for a method or a function within a class is public. So to some extent, it's redundant.
within a class is public. So to some extent, it's redundant. Now, having said that, it's just common practice to declare visibility these days. So even though public is the default, I would recommend just getting the practice of being explicit. And as you'll learn in the future, there are other visibilities, like protected and private. But for now, we're just going to make everything open to the outside world. Okay, so let me give this a quick reformat to clean it up. And when we breathe, well, what should we do there? Well, remember, functions are the verbs of the programming world, including methods. So why don't we just say echo, and to start, I will write breathing.
Well, remember, functions are the verbs of the programming world, including methods. So why don't we just say echo, and to start, I will write breathing. All right, so how do we work with this Person class? Because remember, I did say it's sort of like a blueprint, right? And just like, hmm, for a home construction, you'll have blueprints, right? But then you could have any number of homes that you build off of those blueprints. Maybe this one is brown, and this one is white, but it's still working off the same blueprint. Well, you could refer to those homes as implementations or instances of the blueprint. And we're going to do the exact same thing here. $person equals a new Person, just like that, with the new keyword.
And we're going to do the exact same thing here. $person equals a new Person, just like that, with the new keyword. All right, next, let's set the name and age of the person. $person->name equals John Doe. And right here, hmm, this isn't ideal for a video. This arrow is actually a dash and then a greater than sign, but I'm using a fancy font that turns it into an arrow. But yeah, on your own, you may not see that. Just put them next to each other. Okay, so notice I'm referencing this property,
Just put them next to each other. Okay, so notice I'm referencing this property, but I don't type it out like a normal variable. Notice that I omitted the $ sign. All right, let's do it again. personAge equals, how about 25? Okay, so now let's use our handy-dandy dd function to die and dump this person and inspect it. All right, switch back and we'll give this a refresh. And oh, you know what? I'm sorry.
All right, switch back and we'll give this a refresh. And oh, you know what? I'm sorry. Just for a moment, I need to comment out the router. All right, let's do it again. And there we go. So now notice an instance of a class is referred to as an object. And for this object, the name is set to John Doe and the age is 25. If I want to access them, it's very similar to an associative array. But instead of doing this syntax,
it's very similar to an associative array. But instead of doing this syntax, I once again use the arrow syntax that we learned about. So person name, and that should give me John Doe. Change it to age. That'll give me 25. And then why don't we call some of the behavior on this class? breathe, all right? breathe and call it just like a normal function. Okay, come back, give this a refresh.
Breathe and call it just like a normal function. Okay, come back, give this a refresh. And now, yeah, I have called that function or called that method. Pretty cool. And even better, within our class, we can interact with these instance properties. So for example, what if I wanted to say JohnDoe is breathing? I could say echo $this, and this is a keyword that refers to the current instance.
I could say echo this, and this is a keyword that refers to the current instance. I think of it as this instance. All right, this name and then a space is breathing. Okay, so now, because we're calling echo, I don't need dd as well, so I can remove that. And let's give it a shot. Come back, refresh, John Doe is breathing. And yeah, I can create as many instances of this class as I want.
And yeah, I can create as many instances of this class as I want. One named John, another named Jane, who is 45. But again, they all work off the same blueprint. So yeah, that's your two-minute classes 101 introduction. Trust me, we will go into this in quite a bit more detail in the future. So back to work. All of that to show you that to connect to MySQL, we need to create a new instance of the PDO class.
Building the PDO DSN8:45
All of that to show you that to connect to MySQL, we need to create a new instance of the PDO class. Now you can see this class expects an argument called DSN. DSN stands for data source name. Again, this stuff is very confusing. Think of it as a connection string, a string that declares your connection to the database. So what port, what host, what database name, what character set, things like that. Let's define it now.
I said to remember this, the host is localhost. And then I can divide these key value pairs with a semicolon. So the port is 3306. And yeah, just in case you forgot how to find that, you can, I think, click right up here. And yeah, host 127.0.0.1 is localhost. And then the port, maybe you have to close this out. Right click and go to edit. Here we go.
Right click and go to edit. Here we go. Port 3306. Here's the username. Here's the database. Okay, cool. So let's go back and now declare our database name. $dbName equals myApp. And then finally, I'm going to, as a good practice, declare the character set.
You don't really need to worry about it. Okay. And I will save this as PDO. All right, next, we should probably handle situations where php was unable to connect. And to do that, we would use something known as a try-catch statement. But again, it's a new thing that we haven't yet learned. So forgive me, but I'm going to skip it just for now,
Preparing and Executing Queries10:46
But again, it's a new thing that we haven't yet learned. So forgive me, but I'm going to skip it just for now, but we'll cover it later. Anyways, I'm ready to prepare a new query. Prepare. And yeah, you'll remember what was our query up here. SELECT * FROM posts. So I will copy that. Switch back and paste it in.
So I will copy that. Switch back and paste it in. Prepare this new query. So yeah, we are effectively preparing this query to send to MySQL where it will be executed. So we often call this variable statement. It is a prepared query statement. And then again, I said, we send it to MySQL to execute. So I will call a method named execute. And remember, method, function, kind of interchangeable,
So I will call a method named execute. And remember, method, function, kind of interchangeable, but the proper term is a function on a class is called method, but it doesn't really make a difference. Okay, so now the only remaining step is to fetch the results. So I can say $post equals $statement, and let's use fetchAll. I want to fetch all of the results as opposed to a single result or a single record.
I want to fetch all of the results as opposed to a single result or a single record. Okay, so cross your fingers. Let's pass this to Didi and see what we come up with. So I give it a run and actually it fails. So we screwed up. Access denied for user at localhost. Yeah, I forgot to provide the username. And you'll remember that the username is root. So I could do that as part of our DSN,
And you'll remember that the username is root. So I could do that as part of our DSN, or I could even do it as the second argument like so. So if I come back and give this a refresh, now it works. Or again, you can do it directly within the DSN like this, user equals root. And if there's a password, you would provide that as well. Okay, come back, refresh, and now it works. All right, so have a look at what we get in response. I have an array of arrays where each item
Fetching and Displaying Results12:32
All right, so have a look at what we get in response. I have an array of arrays where each item is a record that came from MySQL. So notice if we have a look here, the first record has an ID of one and a title of my first blog post. Sure enough, an ID of one and a title of my first blog post. But notice we have a little bit of duplication here. Notice here's a key of ID and then zero, and then here's a key of title and then one.
Notice here's a key of id and then zero, and then here's a key of title and then one. So notice it's kind of giving us both versions, a keyed version and an indexed version. But really, in most cases, you don't want that. So there's a number of ways to do that. But for now, I'm going to declare how I wanna fetch the results like this. PDO::fetch, and why don't we say PDO::FETCH_ASSOC. Give me the results as an associative array.
PDO, fetch, and why don't we say associative array. Give me the results as an associative array rather than indexed. So now notice if I come back and refresh, we will remove that duplication. And this is probably what you want. So now to wrap up, of course, we have way more to do, but to wrap up this video, we can play around by, we'll do it inline here. And we could say echo a list item.
we can play around by, we'll do it inline here. And we could say echo a list item and then the title of the Post and then a closing list item. And with any luck, we have the results. Okay, so I know we covered a lot here. There's a lot of confusing stuff and there's more to come, but it wasn't that many lines of code. We figured out this confusing connection string. We created our first instance of a class.
We figured out this confusing connection string. We created our first instance of a class. We prepared a new query to send to MySQL. MySQL executed that query and then we fetched all of the results and then we looped over them and displayed the results. So yeah, more to do here, but you're making really good progress. Stay tuned. ♪ Click, click, click, click ♪
