ведение истории данных формы с использованием сессии - PullRequest
0 голосов
/ 13 июня 2018

У меня есть форма, которую пользователи могут использовать, чтобы ввести некоторые данные для создания значка.Я использую сессию, чтобы я мог вести небольшой список истории для пользователей, а также, если они щелкают по одному элементу из этого списка, данные будут автоматически отправляться в форму.Моя проблема в том, что, когда я нажимаю на один элемент из списка, вставляется новая строка, содержащая те же данные, а также, если я снова заполняю форму с идентичными данными, которые у меня уже есть в моем списке, он создает другую строку, содержащую те же данные, которыеу меня уже есть один раз.Могу ли я сделать что-то, чтобы мой список истории содержал только уникальные значения, в основном, чтобы не иметь одну и ту же строку несколько раз.Это мой код для формы:

<form method="get" autocomplete="off">
    <h3>Creaza ecuson</h3>
    <label>
        Nume:<br><input type="text" name="nume" id="nume" required value="<?php echo $search->nume ?>"><br>
        Prenume:<br><input type="text" name="prenume" id="prenume" required value="<?php echo $search->prenume ?>"><br>
        Sex:<br><div class="autocomplete" style="width:300px;">
                                <input id="sex" type="text" name="sex" required value="<?php echo $search->sex ?>">
                     </div><br><br>
        Rol:<br><div class="autocomplete" style="width:300px;">
                                <input id="rol" type="text" name="rol" required value="<?php echo $search->rol ?>">
                     </div><br><br>
        Culoare text:<br><input type="color" name="cul" id="cul" value="<?php echo $search->cul ?>"><br><br>
        Font ecuson:<br><div class="autocomplete" style="width:300px;">
                                <input id="font" type="text" name="font" required value="<?php echo $search->font ?>">
                     </div><br><br>
        Format ecuson (portrait or landscape):<br><div class="autocomplete" style="width:300px;">
                                <input id="format" type="text" name="format" required value="<?php echo $search->format ?>">
                       </div><br><br>
    </label>
    <input type="submit" name="history" value="History" />
    <button type="button" onclick="create()">Creaza</button><br><br>
</form>

Мой код сеанса:

<?php
        session_start();

        $search = parseRequest();
        storeSearch($search);

        include "form.php";

        $searches = $_SESSION['searches'];


        function storeSearch($search) {
            if (!isset($_SESSION['searches'])) {
                $_SESSION['searches'] = [];
            }

            if (!$search->isEmpty()) {
                $_SESSION['searches'][] = $search;
            }
        }


        function parseRequest() {
            $search = new SearchRequest;
            $search->nume = !empty($_GET['nume']) ? $_GET['nume'] : "";
            $search->prenume = !empty($_GET['prenume']) ? $_GET['prenume'] : "";
            $search->sex = !empty($_GET['sex']) ? $_GET['sex'] : "";
            $search->rol = !empty($_GET['rol']) ? $_GET['rol'] : "";
            $search->cul = !empty($_GET['cul']) ? $_GET['cul'] : "";
            $search->font = !empty($_GET['font']) ? $_GET['font'] : "";
            $search->format = !empty($_GET['format']) ? $_GET['format'] : "";
            return $search;
        }

        /**
         * search request
         */
        class SearchRequest
        {
            public $nume = "";
            public $prenume = "";
            public $sex = "";
            public $rol = "";
            public $cul = "";
            public $font = "";
            public $format = "";

            function toQueryString() {
                $params = [
                        'nume' => $this->nume,
                        'prenume' => $this->prenume,
                        'sex' => $this->sex,
                        'rol'=> $this->rol,
                        'cul'=> $this->cul,
                        'font'=> $this->font,
                        'format'=> $this->format
                ];

                return http_build_query($params);
            }

            function isEmpty() {
                return !$this->nume || !$this->prenume || !$this->sex || !$this->rol || !$this->cul || !$this->font || !$this->format;
            }
        }

        ?>

И так называемый код истории:

<?php
            foreach ($searches as $s) {
            ?>
             <li><a href="creare.php?<?php echo $s->toQueryString() ?>">
                    <?php echo $s->nume?> - <?php echo $s->prenume?> - <?php echo $s->sex?> - <?php echo $s->rol?> - <?php echo $s->cul?> - <?php echo $s->font?> - <?php echo $s->format?>
                  </a></li>
            <?php
            }
            ?>

Я недумаю, что сценарий с функцией автозаполнения должен быть размещен здесь для вопроса, который я задал.При необходимости я предоставлю.

Ответы [ 3 ]

0 голосов
/ 13 июня 2018

Вот способ и небольшой псевдокод, вы могли бы реализовать нечто подобное с вашей кодовой базой.

Идея состоит в том, что, поскольку с одного компьютера может зарегистрироваться только один человек, сохраните уникальный идентификатор для этого человека всессия.Затем при вводе данных в сеанс проверьте, присутствует ли этот идентификатор.

Если он присутствует, не добавляйте, если нет, добавьте.

Псевдокод

$uniqueID = hash("sha256", $_SERVER['REMOTE_ADDR']); //generate a unique ID depending on IP since that would be unique for each computer

//insert into your session
if(!in($sessionHandler, $uniqueid)
{
    //insert now
}
0 голосов
/ 13 июня 2018

Опираясь на ответ службы поддержки CFP, здесь немного отличается подход к созданию формы и обработчика.Это очень похоже на вашу, но я структурировал логику немного по-другому.Я только добавил 3 поля из вашей формы, но вы можете легко добавить остальные поля.

Скрипка - http://phpfiddle.org/lite/code/354t-6sgn

<code><?php

session_start();

// Initialize the cart if it needs it.
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = [];
}

// Should we show cart?
$showCart = isset($_GET['cart']) && $_GET['cart'] === 'true';

// Should we clear the cart?
if (isset($_GET['clear']) && $_GET['clear'] === 'true') {
    $_SESSION['cart'] = [];
}

// Grab the current cart.
$cart = $_SESSION['cart'];

// The form was submitted
if (isset($_POST['submit'])) {

    // Copy the POST data into a variable so we can modify it without side effects.
    $formData = $_POST;

    // Remove the submit button from the form data
    unset($formData['submit']);

    // Check if it is in the cart already.
    if (!in_array($formData, $cart)) {
        // If not, then add it.
        $cart[] = $formData;
    }

    // Store the cart in the session.
    $_SESSION['cart'] = $cart;
}
?>


<html>
<head>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>

<body>
<div class="container">
    <form method="post" autocomplete="off">
        <h3>Creaza ecuson</h3>
        <div class="mb-3">
            <div class="col-md-6 mb-3">
                <label for="nume">Nume:
                    <input type="text" name="nume" id="nume" class="form-control" required>
                </label>
            </div>
        </div>


        <div class="mb-3">
            <div class="col-md-6 mb-3">
                <label for="prenume">Prenume:
                    <input type="text" name="prenume" id="prenume" class="form-control" required>
                </label>
            </div>
        </div>


        <div class="mb-3">
            <div class="col-md-6 mb-3">
                <label for="sex">Sex:
                    <input type="text" name="sex" id="sex" class="form-control" required>
                </label>
            </div>
        </div>

        <button class="btn btn-primary" name="submit" type="submit">Create</button>

        <?php
        // Toggle show/hide history
        if ($showCart) { ?>
            <a class="btn btn-primary" href="?" role="button">Hide Cart</a>
        <?php } else { ?>
            <a class="btn btn-primary" href="?cart=true" role="button">Show Cart</a>
        <?php }

        // If the cart is not empty, allow user to clear it.
        if (!empty($cart)) { ?>
            <a class="btn btn-primary" href="?clear=true" role="button">Clear Cart</a>
        <?php }
        ?>

    </form>

    <?php
    // Show the cart.
    if ($showCart) {
        echo '<pre>';
        var_dump($cart);
        echo '
';}?>
0 голосов
/ 13 июня 2018

возможно что-то простое, как

function storeSearch($search) {
        if (!isset($_SESSION['searches'])) {
            $_SESSION['searches'] = [];
        }

        if (!$search->isEmpty() && !in_array($search,$_SESSION['searches') {
            $_SESSION['searches'][] = $search;
        }
    }
...