Skip to content

Getting Started Using Database

Introduction

To use the database in your PHP application, you first need to modify the core/database.php file. Open this file in a text editor and modify the following settings:

  • DB_CONNECTION: Change this to the type of database you're using (e.g. mysql, postgres, sqlite).
  • DB_HOST: Change this to the hostname of your database server.
  • DB_PORT: Change this to the port number of your database server (e.g. 3306 for MySQL).
  • DB_NAME: Change this to the name of your database.
  • DB_USER: Change this to the username for your database.
  • DB_PASS: Change this to the password for your database.

After updating the settings, you can start using the database in your PHP code. To do this, you can use the DB class provided in core/DB.php. This class provides a simple and easy-to-use interface for executing SQL queries and fetching results.

Here is an example of how to use the DB class to execute a SQL query:

// Import the DB class
use App\Core\DB;

// Execute a SQL query and fetch all results
$query = "SELECT * FROM users";
$results = DB::query($query)->fetchAll(PDO::FETCH_ASSOC);

// Print the results
foreach ($results as $result) {
    echo $result['name'] . '<br>';
}

In this example, we first import the DB class using the use statement. Then, we execute a SQL query to select all users from the database using the DB::query() method. Finally, we loop through the results and print out the name of each user.

Note that the DB::query() method takes two parameters: the SQL query to execute and an optional array of parameters to bind to the query. If you need to bind parameters to your query, you can pass them in as an array like this:

// Execute a SQL query with parameters
$query = "SELECT * FROM users WHERE id = :id";
$data = ['id' => 1];
$results = DB::query($query, $data)->fetchAll(PDO::FETCH_ASSOC);

In this example, we execute a SQL query to select a user with ID 1 from the database. We pass the ID as a parameter using an array, which is then bound to the query using the : notation.

That's it! You're now ready to start using the database in your PHP application.