tag, which is used to pass data to the background, but not displayed on the page. This is the hidden field. in P"/> tag, which is used to pass data to the background, but not displayed on the page. This is the hidden field. in P">

Home  >  Article  >  Backend Development  >  How to pass array through hidden field in php

How to pass array through hidden field in php

PHPz
PHPzOriginal
2023-04-19 11:40:44469browse

In web development, we often need to use forms to collect user input information. However, in some cases, we need to pass some data to the background processing at the same time, and these data do not require user input or display. At this time, you can use hidden fields to pass this data. In PHP development, we can pass an array through hidden fields.

What is a hidden field?

In HTML, there is an tag, which is used to pass data to the background but not displayed on the page. This is the hidden field.

In PHP, we can also define a hidden field through the tag to pass data to the server.

How to pass array?

If you want to pass an array, you need to serialize the array and then store it in the hidden field. For example, the following code can serialize an associative array and store it in a hidden field:

<form method="post" action="process.php">
    <input type="hidden" name="data" value="<?php echo htmlspecialchars(json_encode($data)); ?>">
    <input type="submit" value="Submit">
</form>

In the above code, we define a hidden field named "data" and store the associative array After $data is serialized, it is assigned to the "value" attribute of this hidden field. Note that before we store the hidden field, we first use PHP's built-in json_encode() function to serialize the associative array into a JSON string.

On the server side, we can use the json_decode() function to deserialize the JSON string into an associative array. For example, the following code can parse the hidden field passed earlier into an associative array:

$data = json_decode($_POST['data'], true);

In the above code, we use $_POST['data'] to obtain the serialization stored in the hidden field The resulting JSON string is then deserialized into an associative array using the json_decode() function.

It should be noted that we need to set the second parameter to true in order to convert the result into an associative array.

Example demonstration

In order to better understand the principle and implementation of hidden field transfer array, below we provide an example demonstration. This example is a simple message board system. After the user leaves a message, the message content is stored in the MySQL database and the message list is displayed on the page.

First, let’s take a look at the front-end code, which is responsible for rendering the message form and message list:

<!DOCTYPE html>
<html>
<head>
    <title>Message Board Demo</title>
</head>
<body>
    <h1>Message Board Demo</h1>
    <form method="post" action="process.php">
        <p><label>Your Name:</label><br><input type="text" name="name"></p>
        <p><label>Message:</label><br><textarea name="message"></textarea></p>
        <input type="hidden" name="action" value="add">
        <p><input type="submit" value="Submit"></p>
    </form>
    <hr>
    <h2>Message List</h2>
    <ul>
        <?php foreach ($messages as $message) : ?>
            <li><?php echo htmlspecialchars($message[&#39;name&#39;] . &#39;: &#39; . $message[&#39;message&#39;]) ?></li>
        <?php endforeach; ?>
    </ul>
</body>
</html>

In the above code, we define a form where users can enter their name and message content , and then click the "Submit" button to submit the form. In the form, we define a hidden field to pass a command line parameter "action" to tell the background what operations we want to perform. Here, we set "action" to "add", indicating that we want to add a new message.

After the form is submitted, we need to send the name and message content entered by the user to the server for processing. The specific processing logic is implemented in the background PHP code.

The following is the back-end code to handle the adding and reading operations of comments:

<?php
// 连接到数据库
$conn = new mysqli(&#39;localhost&#39;, &#39;username&#39;, &#39;password&#39;, &#39;database&#39;);

// 检查连接是否成功
if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
}

// 处理留言添加操作
if ($_POST['action'] == 'add') {
    $name = $_POST['name'];
    $message = $_POST['message'];
    $sql = "INSERT INTO messages (name, message) VALUES ('$name', '$message')";
    $result = $conn->query($sql);
    if (!$result) {
        die('Error: ' . $conn->error);
    }
}

// 读取留言列表
$sql = "SELECT * FROM messages ORDER BY id DESC";
$result = $conn->query($sql);
if (!$result) {
    die('Error: ' . $conn->error);
}

$messages = [];
while ($row = $result->fetch_assoc()) {
    $messages[] = $row;
}

$conn->close();

In the above code, we first connect to the MySQL database and check whether the connection is successful. Then, based on the submitted "action" parameter, determine what operation the user wants to perform.

If the "action" parameter is "add", it means that the user wants to add a new message. We get the name and message content entered by the user from the $_POST array, and then use the insert statement to write the message content into the MySQL database.

If the "action" parameter is "read", it means that the user wants to read the message list. We query all message records from the MySQL database and store the results in an associative array $messages.

Finally, we close the connection to the MySQL database and pass the $messages array to the front-end code so that the user can see the message list.

Conclusion

Through the above example demonstration, we can see how to use hidden fields to pass arrays. In daily web development, we often need to pass some data to the background for processing at the same time without user input or display. Using hidden fields can accomplish this function well, and using arrays can improve the flexibility of data transfer, making our programs easier to develop and maintain.

The above is the detailed content of How to pass array through hidden field in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn