PHP Обновление структуры статей

@import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap');

<!-- begin snippet: js hide: false console: true babel: false -->
<div class="container">
    <div class="card">
        <div class="content">
            <?php

            $articles = mysqli_query($connection, "SELECT * FROM `articles` ORDER BY `views`");

            while ($art = mysqli_fetch_assoc($articles)) {
                    ?>

                    <h2>
                    <?php
                        if ($art['id'] >= 10) {
                            echo $art['id'];
                        } else {
                            echo '0' . $art['id'];
                        }

                    ?>
                        
                    </h2>
                    <h3>
                        <?php echo mb_substr($art['title'], 0, 20, 'utf-8'); ?>   
                    </h3>

                    <p><?php echo mb_substr($art['description'], 0, 120, 'utf-8') . "..."; ?></p>

                    <a href="/project.php?id=<?php echo $art['id']; ?>">Read More</a>

            <?php
                }
                ?>

        </div>
    </div>
</div>

* {
    font-family: 'Poppins', sans-serif;
    -webkit-font-smoothing: antialiased;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}


body {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background: #161623;
}

body::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(#f00, #f0f);
    clip-path: circle(30% at right 70%);
}

body::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(#2196f3, #e91e63);
    clip-path: circle(20% at 10% 10%);
}


.container {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    max-width: 1200px;
    flex-wrap: wrap;
    z-index: 1;
}

.container .card {
    position: relative;
    width: 280px;
    height: 400px;
    margin: 30px;
    box-shadow: 20px 20px 50px rgba(0, 0, 0, .5);
    border-radius: 15px;
    background: rgba(255, 255, 255, .1);
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    border-top: 1px solid rgba(255, 255, 255, .5);
    border-left: 1px solid rgba(255, 255, 255, .5);
    backdrop-filter: blur(5px); 
}

.container .card .content {
    padding: 20px;
    text-align: center;
    transition: .5s;
    transform: translateY(100px);
    opacity: 0;
}

.container .card:hover .content {
    transform: translateY(0px);
    opacity: 1;
}

.container .card .content h2 {
    position: absolute;
    top: -80px;
    right: 30px;
    font-size: 8em;
    color: rgba(255, 255, 255, .05);
    pointer-events: none;
}

.container .card .content h3 {
    font-size: 1.8em;
    color: #fff;
    z-index: 1;
}

.container .card .content p {
    font-size: 1em;
    color: #fff;
    font-weight: 300;
}

.container .card .content a {
    position: relative;
    display: inline-block;
    padding: 8px 20px;
    margin-top: 15px;
    background: #fff;
    color: #000;
    border-radius: 20px;
    text-decoration: none;
    font-weight: 500;
    box-shadow: 0 5px 15px rgba(0, 0, 0, .2);
}
<?php include '../includes/config.php'; ?>

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="../../media/assets/css/projects.css">
    <link rel="shortcut icon" href="../../media/assets/img/favicon.jpg" type="image/png">
    <title>Projects</title>
</head>

<body>
    <?php include "../includes/project.php"; ?>
    
    <script type="text/javascript" src="../../media/assets/js/vanilla-tilt.js"></script>
    <script>
      VanillaTilt.init(document.querySelectorAll(".card"), {
        max: 20,
        speed: 100,
        glare: true,
        "max-glare": 0.5,
    });
    </script>
</body>

</html>

Есть страница проектов. На ней должны показываться карточки, а в карточках данные(id, text etc.). Как мне разбить карточки так, чтобы каждая карточка имела своё название и текст. (в бд всё это присутствует)


Ответы (1 шт):

Автор решения: Егор Банин

Хорошая структура -- это не прихоть зануд-красноглазиков и не финишная полировка кода. Это то, что позволит вам быстро решать проблемы. Ваши проблемы. Пока вам не охота переписывать и вы ждёте решений на so, ваши сверстники уже решают проблемы следующего уровня.

Разделив получение данных и их отображение, вы можете проверить каждую часть независимо. Если ошибка в получении данных, то весь html не имеет смысла. Если с данными всё ок, то не надо изучать запросы в базу данных.

Ваш вопрос посмотрело больше 20 человек, но никто не захотел разбираться, потому что ничего не понятно :-) Хорошая структура помогла бы вам и тут.

Я накидал пример для вас. Я подделал ответ из базы данных, чтобы вы могли запустить код, если потребуется.

index.php

<?php

// php -S localhost:8000

// ...
$connection = 'fake connection';
$articlesResult = _mysqli_query($connection, "SELECT * FROM `articles` ORDER BY `views`");
$articles = [];
while ($row = _mysqli_fetch_assoc($articlesResult)) {
    $articles[] = $row; // тут только получаем данные, не отображаем
}

//var_dump($articles);die; // var_dump -- самый примитивный способ отладки; используйте, чтобы понять, что происходит в вашем приложении

$articlesHtml = ob_include(__DIR__ . '/articles.phtml', ['articles' => $articles]); // тут только отображаем
echo ob_include(__DIR__ . '/layout.phtml', ['content' => $articlesHtml]);


/**
 * Подключение файла с буферизацией вывода
 * @param string $file
 * @param array $params
 */
function ob_include(): string
{
    extract(func_get_arg(1));
    ob_start();
    require func_get_arg(0);
    return ob_get_clean();
}

// -------------------------------------------------------------------------------
// я сделал заглушки функций mysqli, чтобы вы могли попробовать без заморочек с бд

function _mysqli_query($connection, $sql) {
    return 'fake result';
}

function _mysqli_fetch_assoc($result) {
    static $rows = [
        ['id' => 1, 'title' => 'Laravel', 'description' => 'Laravel is a web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.'],

        ['id' => 2, 'title' => 'Gulp', 'description' => 'Leverage gulp and the flexibility of JavaScript to automate slow, repetitive workflows and compose them into efficient build pipelines.'],
    ];

    $row = current($rows);
    next($rows);

    return $row;
}

articles.phtml

<div class="container">
    <?php foreach ($articles as $article): ?>
        <div class="card">
            <div class="content">
                <h2><?= htmlspecialchars(str_pad($article['id'], 2, '0', STR_PAD_LEFT)) ?></h2>
                <h3><?= htmlspecialchars($article['title']) ?></h3>
                <p><?= htmlspecialchars($article['description']) ?></p>
                <a href="/project.php?id=<?= htmlspecialchars($article['id']) ?>">Read More</a>
            </div>
        </div>
    <?php endforeach ?>
</div>

layout.phtml

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="../../media/assets/css/projects.css">
    <link rel="shortcut icon" href="../../media/assets/img/favicon.jpg" type="image/png">
    <title>Projects</title>
</head>

<body>
    <?= $content ?>
    
    <script type="text/javascript" src="../../media/assets/js/vanilla-tilt.js"></script>
    <script>
      VanillaTilt.init(document.querySelectorAll(".card"), {
        max: 20,
        speed: 100,
        glare: true,
        "max-glare": 0.5,
    });
    </script>
</body>

</html>

Чтобы запустить этот пример, надо создать в отдельной папке три файла (index.php, articles.phtml, layout.phtml) и выполнить в консоли php -S localhost:8000, потом открыть http://localhost:8000 и посмотреть результат.

Но сперва посмотрите внимательно на articles.phtml. Обратите внимание, что блок card выводится внутри цикла (то есть на каждую статью один блок card). Теперь посмотрите в свой код. У вас блок card за пределами цикла (то есть все статьи внутри одного блока card).

→ Ссылка