How to render notes and note page in php?
Ghulam Mujtaba
Posted on June 21, 2024
Firstly,
-
Create a table in the database named "notes" with the following columns:
- id (unique index)
- title
- content
The "id" column is the primary key and has a unique index, allowing for efficient location of specific data.
The "title" column stores the note title.
The "content" column stores the note content.
-
Sample data in the "notes" table:
- id | title | content
- --- | --- | ---
- 1 | Note 1 | I am a frontend developer .
- 2 | Note 2 | I am a backend developer .
- 3 | Note 3 | I am a blogger.
- 4 | Note 4 | I am a YouTuber.
The unique index on the "id" column enables fast lookup and retrieval of specific notes by their ID.
Diving in code
In a fresh vs code project (version 1.90 at the time of working), we need two different files to easily learn the working of code.
On VS Code Side
Create two files named notes.php
and note.php
.
- The "notes.php" file is used to:
- Fetch all notes from the database
- Display a list of all notes on the screen While,
- The "note.php" file is used to:
- Fetch a single note from the database using its unique ID (index)
- Display the content of a single note on the screen
Connection to database
- As before fetching notes, a connection with the database must be made and configured as described earlier.
Add Notes link in nav file
- Add a link in the navigation file (nav.php) that, when clicked, directs to the notes screen (notes.php).
<a href="notes.php">Notes</a>
Different notes are showing on that page.
<?php
$config = require('config.php');
$db = new Database($config['database']);
$heading = 'My Notes';
$notes = $db->query('select * from notes where user_id = 1')->fetchAll();
require "views/notes.view.php";
But when a user wants to view a specific note on the screen, a superglobal variable (e.g., $_GET or $_POST) is used to retrieve the note ID from the user's request, and then the corresponding note is displayed on the screen.
<?php
$config = require('config.php');
$db = new Database($config['database']);
$heading = 'Note';
$note = $db->query('select * from notes where id = :id', ['id' => $_GET['id']])->fetch();
require "views/note.view.php";
If the user enters the wrong id to find note that is not in database table then a 404 error page is shown on screen with a link 🖇️ to go back to home.
I hope that you have clearly understand each and everthing easily.
Posted on June 21, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.