This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
The PHP Data Object (PDO) allows PHP to interact with a database. This project uses a SQLite database, but you can connect to many different types of databases using a PDO. This video will show you how to find and use the documentation for PDO so you can then use that documentation to connect to other databases as well.
Magic Constants
PHP provides a large number of predefined constants to any script which it runs. More information on these Magic Constants can be found here.
Connecting PDO to MySQL
$db = new PDO("mysql:host=localhost;dbname=DATABASE_NAME;port=3306","USERNAME","PASSWORD");
For MySQL, you specify mysql and a colon, then type "host=" followed by the name of the host to which you want to connect. After that, you type a semicolon, followed by dbname and an equal sign, followed by the name of the database. If your environment is using the default MySQL port of 3306, this string here might be all you need.
MAMP uses a different port (8889 by default), so if you haven't changed the default, you will have to specify the port number. You type another semicolon, followed by the word "port" and an equal sign, followed by the port number.
That's the first argument to pass in when instantiating a new object from the PDO class. It's all surrounded by 1 set of quotation marks because it's 1 PHP string.
The word βhostβ, here, is not a PHP variableβ it's just part of a piece of text that gets used to identify the database.
For MySQL, the second argument is the username and the third argument is the password. By default, the MySQL username and password on MAMP are both "root".
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up