Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine

Talking to Databases in PHP

Keep on Learning!

If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.

Start your All-Access Pass
Buy just this tutorial for $12.00

Talking to Databases in PHP

If you don’t have the code for the project downloaded yet, get it now. After it downloads, unzip it. Perfect! All we need to do now is start the built-in PHP web server so we can execute our code. Open up a terminal, move into the directory where you just unzipped the code, and start the server:

php -S localhost:8000

Unless I’ve messed something up, I should be able to go to http://localhost:8000 and see our site. There it is!

Connecting to MySQL in PHP

We’re about to take a huge step by talking to our database from inside our code. Actually, making queries from PHP is simpler than what we did in the last few chapters. But just like before, step 1 is to connect to the server. Open up index.php and create a new PDO object. This shows off a new syntax which we will cover in a second:

// index.php

$pdo = new PDO('mysql:dbname=air_pup;host=localhost', 'root', null);
// ...

This creates a connection to the server, but doesn’t make any queries. It’s the PHP version of when we typed the first mysql command in the terminal to the server.

Before we dissect it, let’s query for our pets! We’re going to use a function called query but with a new syntax. Set the result to a $result variable. Next, call another function called fetchAll and set it to a $rows variable. Dump $rows so we can check it out:

// index.php

$pdo = new PDO('mysql:dbname=air_pup;host=localhost', 'root', null);
$result = $pdo->query('SELECT * FROM pet');
$rows = $result->fetchAll();
var_dump($rows);
// ...

Ready to see what the data looks like? Refresh your homepage.

Hey, it’s an array with 2 items: one for each row in the pet table. Each item is an associative array with the column names as keys. For convenience, it also repeats each value with an indexed key, but we won’t need that extra stuff, so pretend it’s not there.

What’s really cool is that the array already looks like the one that get_pets gives us. If we temporarily comment out that function and use the array from the database by renaming $rows to $pets, our page should work!!

// index.php
// ...
$pdo = new PDO('mysql:dbname=air_pup;host=localhost', 'root', null);
$result = $pdo->query('SELECT * FROM pet');
$pets = $result->fetchAll();

require 'lib/functions.php';

//$pets = get_pets();

// ...

Refresh! No errors, and the page shows 2 pets. Sure, they’re not very interesting since our 2 pets don’t have age, weights, bios or images, but we could fill those in easily in PHPMyAdmin.

Leave a comment!

7
Login or Register to join the conversation
CloudCreators Avatar
CloudCreators Avatar CloudCreators | posted 1 year ago

PHP Fatal error: Uncaught PDOException: could not find driver in /Users/shubham/AirPup/index.php:2
Stack trace:
#0 /Users/shubham/AirPup/index.php(2): PDO->__construct('mysql : dbname=...', 'root', 'Titanic@123')
#1 {main}
thrown in /Users/shubham/AirPup/index.php on line 2
[Sat Jul 3 18:50:40 2021] [::1]:58302 [500]: / - Uncaught PDOException: could not find driver in /Users/shubham/AirPup/index.php:2
Stack trace:
#0 /Users/shubham/AirPup/index.php(2): PDO->__construct('mysql : dbname=...', 'root', 'Titanic@123')
#1 {main}
thrown in /Users/shubham/AirPup/index.php on line 2

I am stuck at this, I dont have server installed on my mac but why this PDO line is creating such errors I have the pdo_mysql module in my php

Reply

Hey Shubham,

Hm, please, make sure your DB credentials are correct first and you didn't make any typos in it. If everything looks good, try to restart the server, I'd recommend you to restart your laptop just in case and try again. The error really sounds like you don't have pdo_mysql module, maybe if you started the server and installed it after - the already running server does not see it, so you have to restart.

If you're still experiencing this error even after laptop restart - please, share a bit more information, what do you do to see this error? Do you run it in your terminal? What command? What OS do you use?

I hope this helps!

Cheers!

Cheers!

Reply

hey,
we didn't talked about the object-operator -> yet. Did we?? Would be nice to introduce that...

happy I found https://stackoverflow.com/questions/3037526/where-do-we-use-the-object-operator-in-php

Aha, there is also a scope operator :: hm, hm ...

Reply

Hey Henrik Pantle !

Ah, you're right! We talk about that in the NEXT chapter - https://symfonycasts.com/sc... - so I was just a minute too early! I think I wanted to get some "database query" success before we dove into some object-oriented stuff. So, while we "touch" on the object-oriented stuff in this tutorial, we have a few other proper tutorials on that topic - https://symfonycasts.com/sc...

From an object-oriented perspective, the -> operator is use to call a method on an instance of an object. The :: is used to call a static method on a class. We actually don't talk at all about static methods until episode 4 of our object oriented series - https://symfonycasts.com/sc... - in part because they "should be" rarely used (using objects typically will lead you to better code) and so I only wanted to introduce them later.

Anyways, I probably just dumped more details than you needed - but let me know if this is helpful or if you have any other questions :).

Cheers!

Reply

Thank You Ryan.
And Sorry. Five minutes after my post I was taught not to be too fast in wondering....
Stay save and happy holidays to all of the team!

Reply
Lucio S. Avatar
Lucio S. Avatar Lucio S. | posted 3 years ago

I'm not using xampp to go through these examples. Just thought I'd point out that I had to change 'host=localhost' in the PHP code to 'host=127.0.0.1' in order to get this to work. Loving the tutorials though ;)

Reply

Hey Lucio Eastman!

Good tip! 127.0.0.1 is probably better anyways - that's your REAL local IP address. Most systems also allow "localhost" as a sort of alias to 127.0.0.1... but as you proved, 127.0.0.1 is more portable because it *always* works :).

Cheers!

Reply
Cat in space

"Houston: no signs of life"
Start the conversation!