Viewers: in countries Watching now:
Now that PHP has true object-oriented capabilities, it's best practice to access databases using PDO (PHP Data Objects) and MySQLi. These methods produce database-neutral code that works with over a dozen systems, including MySQL, SQL Server, PostgreSQL, and SQLite. Learn how to use PDO and MySQLi to perform basic select, insert, update, and delete operations; improve security with prepared statements; and use transactions to execute multiple queries simultaneously. Author David Powers also covers advanced topics like instantiating custom objects, and compares PDO to MySQLi so you can decide which method is right for you.
In this chapter, we'll take a look at basic database operations using PDO. Before you can do anything with PDO, you need to create a database source name or DSN. This is simply a string that identifies the database you want to connect to. It begins with a prefix indicating the database system you're using. The prefix is followed by a colon and a series of name/value pairs. That specify the location of the server, the database name, and any other details needed to establish the connection.
Each pair is separated by semicolons. Each database driver uses a different format for the DSM. Let's take a look at a few examples. The prefix for MySQL is mysql. The driver uses the host for the server and dbname for the database. If you're connecting to MySQL on a nonstandard port, you need to specify that as a separate name value pair. The dear send for SQLite3 is the prefix SQLite followed by a fully qualified path to the database file.
Prefix for Microsoft SQL Server is sqlsrv. The DSN uses server instead of host and database instead of dbname. These are just simple examples that don't cover all available options, such as changing the default character set. You can check which options are available for each PDO driver in the PHP documentation at the address shown here. Although the details for each database are different, only the DSN is database-specific.
All other PDO code is database-neutral. So if you switch databases, all you need to do is change the DSN. Everything else should work seamlessly as long your SQL doesn't use features unique to a particular database system.
There are currently no FAQs about Accessing Databases with Object-Oriented PHP.
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.