⊗ppPmSDDb 442 of 447 menu

Database Engine in PHP

Let's now make a website engine where the content of the pages will be stored not in files, but in a database. Suppose we have the following table in the database:

pages
id title content
1 title1 <div> content1 </div>
2 title2 <div> content2 </div>
3 title3 <div> content3 </div>

Suppose we want to get our pages by URLs like /page/1, where the number will represent the id of the page we want to get.

Let's start the implementation. First, in a separate file, we will make a connection to the database and connect this file to ours:

<?php $link = require 'connect.php'; ?>

Get the requested URL:

<?php $url = $_SERVER['REQUEST_URI']; ?>

Using a regular expression, split the URL into parts:

<?php preg_match('#/page/(\d+)#', $url, $match); ?>

Write the id from the capture group into a variable:

<?php $id = $match[1]; ?>

Execute a query to the database, getting the requested page by id:

<?php $query = "SELECT * FROM pages WHERE id=$id"; $res = mysqli_query($link, $query) or die(mysqli_error($link)); $page = mysqli_fetch_assoc($res); ?>

Get the template file:

<?php $layout = file_get_contents('layout.php'); ?>

In the template file, perform the insertion of the title and content:

<?php $layout = str_replace('{{ title }}', $page['title'], $layout); $layout = str_replace('{{ content }}', $page['content'], $layout); ?>

Send the assembled website page to the browser:

<?php echo $layout; ?>

Let's put it all together and get the following code:

<?php require 'connect.php'; $url = $_SERVER['REQUEST_URI']; preg_match('#/page/(\d+)#', $url, $match); $id = $match[1]; $query = "SELECT * FROM pages WHERE id=$id"; $res = mysqli_query($link, $query) or die(mysqli_error($link)); $page = mysqli_fetch_assoc($res); $layout = file_get_contents('layout.php'); $layout = str_replace('{{ title }}', $page['title'], $layout); $layout = str_replace('{{ content }}', $page['content'], $layout); echo $layout; ?>

Implement the described engine. Test its operation.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline