From the course: PHP: Accessing Databases with PDO and MySQLi

Unlock the full course today

Join today to access over 22,400 courses taught by industry experts or purchase this course individually.

Setting an existing object's properties with a database result

Setting an existing object's properties with a database result - PHP Tutorial

From the course: PHP: Accessing Databases with PDO and MySQLi

Start my 1-month free trial

Setting an existing object's properties with a database result

With PDO, you can use the result of a select query to set the properties of an existing PHP object. This is Car.php, which you can find in the chapter four, 04_02 folder of the exercise files. It contains the definition for a custom class called Car. The constructor method takes a single argument, id, and that's used to set the car_id property. The other four properties are set to default values. The class uses the magic set and get methods to set and get the values of properties that don't have their own setter and getter methods. Then down at the bottom, the definition of the magic toString method simply returns HTML to display the objects' properties and their values. So let's create an instance of the Car class. And to do that, I'm going to use fetch_into.php, which you can also find in the exercise files for this video. The page includes the database connection, then the Car class definition. Then it creates an instance of Car and uses echo to display it. So let's see what that…

Contents