Chapters
-
Course Code
Subscribe to download the code!
Subscribe to download the code!
-
This Video
Subscribe to download the video!
Subscribe to download the video!
-
Course Script
Subscribe to download the script!
Subscribe to download the script!
Talking to Databases in PHP
Scroll down to the script below, click on any sentence (including terminal blocks) to jump to that spot in the video!
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.
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.
13 Comments
Hey Lucio S.!
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!
Hi,
When I use PDO module, I. am receiving below error in my web server error_log. I am trying to add this extension PDO module but still having problem.
Have you seen this problem before?
Sun Jan 07 03:27:23.451080 2024] [php:error] [pid 1142] [client 10.212.134.200:55480] PHP Fatal error: Uncaught Error: Class "PDO" not found in /var/www/html/code-php-ep2/start/index.php:3\nStack trace:\n#0 {main}\n thrown in /var/www/html/code-php-ep2/start/index.php on line 3
Hi again,
After searching google, I understand that pdo_mysql
module is missing. I installed by yum install php-pdo_mysql
and checked with php -m
, then restart httpd server. now working.
Additionally, could you please help me to show output of db in nice way? I see as below.
array(3) { [0]=> array(6) { ["id"]=> int(1) [0]=> int(1) ["name"]=> string(10) "Chew Barka" [1]=> string(10) "Chew Barka" ["breed"]=> string(6) "Bichon" [2]=> string(6) "Bichon" } [1]=> array(6) { ["id"]=> int(2) [0]=> int(2) ["name"]=> string(9) "Spark Pug" [1]=> string(9) "Spark Pug" ["breed"]=> string(3) "PUG" [2]=> string(3) "PUG" } [2]=> array(6) { ["id"]=> int(3) [0]=> int(3) ["name"]=> string(12) "Pico de Gato" [1]=> string(12) "Pico de Gato" ["breed"]=> NULL [2]=> NULL } }
Hey Mahmut,
Yes, exactly! Good catch :) You need to install and enable. that pdo_msql
, thanks for sharing it with others!
Additionally, could you please help me to show output of db in nice way? I see as below.
What do you mean?
If you want a nice debug styles - you can leverage Symfony VarDumper component, use dump()
or dd()
to make the debug output nicer :)
Cheers!
actually, when I use var_dump(), it outputs in one line all array. In video, it is shown line per line. How can I enable it on my browser.
for json output, I am using JSONVue.
Hey @Mahmut-A!
I think I know the problem :). There is a PHP extension called "XDebug". If you have this installed, then var_dump()
will output in the fancier way that you see in the video. I bet this is what you need to match the video output you see.
Cheers!
thank you so much. worked
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
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!
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 ...
Hey eltnap !
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!
"Houston: no signs of life"
Start the conversation!
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 ;)