The use of PDO (PHP Data Objects) is one of the most effective methods to interact with databases in PHP. This technology not only provides security through prepared statements but also offers a consistent interface to various database management systems. In this guide, you will learn how to create a simple database model using PDO to retrieve and process data.
Key Takeaways
- PDO is the recommended method for database interaction in PHP 7.
- The separation of logic and database access improves the maintainability of your code.
- The use of a base model combined with specific models allows for a clear structure.
Step-by-Step Guide
1. Create the Model Directory
First, you need to create a new directory for your models. In this directory, you can then create subdirectories for the specific resources. Start by creating a directory named "Model" and a subdirectory "Resource".

2. Create the Base Model
Now you will create your base model that establishes the connection to the database. In the file Base.php in the "Model" directory, create the following structure.
This code creates a new PDO object for the connection to the database. Make sure to adjust the credentials to match your current setup.

3. Create the Image Model
Next, you will create a new model for the resource "Image". This involves extending the base model. This is done in the file Bild.php in the "Model/Resource" directory.
This method getBilder() executes a SQL query to retrieve all images from the database.

4. Fetching Image Data
Now it's time to actually fetch the image data. In your controller, for example in the IndexController, you can instantiate the image model and call the getBilder() method.
Now you have all image data in the variable $bilder and can use it for further processing.

5. Displaying Image Data
To display the retrieved images, you can now create a simple HTML template.
This loop goes through all images and outputs them in HTML format. Be sure to sanitize the data with htmlspecialchars() to avoid potential XSS attacks.

Summary - Database Connection in PHP with PDO
In this guide, you have learned how to implement database connections in PHP using PDO. You created a simple base model that allows you to access specific models and retrieve data from your database. A clear structuring of your models facilitates the maintenance and expansion of your application.