Challenge: PHP Database

Try to implement a database class that connects with the database and a user class that inserts objects in the database.

We'll cover the following

Task

  • Write a class named Db that can connect with the database using the private property $dbh. The class should be able to create the connection with the database, have a method that can get the connection for the use of other classes, and a method to close the connection.

  • Write a User class that can get the database connection and save it in the private property named $dbCon.

  • Write the following methods in the User class that can work with the database:

    • insert(): This method inserts a new user to the users table and returns the id of the last insert.

    • getUserById(): This method is used to return only a single user by ID.

    • getAll(): This method returns all the users.

    • updateUser(): This method is used to update users by id.

    • delete(): This method is used to delete a single user by id.

  • Test your code.

Coding exercise

Since these problems are designed for your practice, try to solve them yourself first. If you get stuck, you can click the “Show Solution” button to see how the problem can be solved. Good luck!

Get hands-on with 1200+ tech skills courses.