简体   繁体   English

将多个输入值存储在数据库的单个字段中并分别进行检索

[英]Storing multiple input values in single field in database and retrieving separately

So, I have a form like so: 所以,我有这样的形式:

<form action="edit.php" method="POST" id="content">
    <h3>Homepage</h3>
    <hr/>
    <h4>Title: </h4><input type="text" name="UserData[]" value='$UserData[]'><br/>
    <h4>Subtitle: </h4><input type="text" name="UserData[]" value='$UserData[1]'><br/>
    <h4>Footer: </h4><input type="text" name="UserData[]" value='$UserData[2]'><br/>
    <input type="submit" value="Save" name="datasave" id="save">
</form>

PHP submit: PHP提交:

if(isset($_POST['datasave']))
{
    $data = $_POST['UserData'];
    $Userdata = mysqli_escape_string($con, $data);
    $query = "UPDATE users 
    SET UserData = '$UserData' WHERE Username = '$Username'";
    mysqli_query($con, $query);
}

Getting values from DB to display in fields: 从数据库获取值以显示在字段中:

$GetUserData = "SELECT UserData FROM users WHERE Username = '$Username'";
$UpdatedUserData= mysqli_query($con,$GetUserData);
if (! $UpdatedUserData){
    echo "error";
}
while($row = mysqli_fetch_assoc($UpdatedUserData)){
    $UserData = $row['UserData'];
}

I should probably note that I am a novice PHP & mysql user (please bear with me). 我可能应该注意,我是PHP和mysql的新手(请多多包涵)。 The problem is, this doesn't work and I'm obviously missing something & not doing this as efficiently as I could be... How can I get the values of my multiple inputs and store them in the same db field? 问题是,这行不通,而且我显然缺少了某些东西,并且没有达到我可能做的那样高效……如何获取多个输入的值并将它们存储在同一个db字段中? As you can see, I'd like each of the values to automatically be added to their respective field on page load. 如您所见,我希望每个值在页面加载时自动添加到它们各自的字段中。

EDIT: I have taken this down to barebones (removing other code etc.) and restructured a bit, which has done the trick! 编辑:我已经把这归结为准系统(删除其他代码等),并进行了一些重组,这已经完成了! Now to learn about parameterized queries :D 现在来了解参数化查询:D

<?php
require('config.php');
session_start();

$Username = $_SESSION['username'];

$GetUserData = "SELECT UserData FROM users WHERE Username = '$Username'";
$UpdatedUserData= mysqli_query($con,$GetUserData);

$row = mysqli_fetch_assoc($UpdatedUserData);

$data = json_decode($row["UserData"]);


foreach($data as $eachdata ) {
    $UserData[] = $eachdata;
}
if ( $UserData ) {
    echo '<form action="edit.php" method="POST" id="content">
              <h3>Homepage</h3>
              <hr/>
              <h4>Title: </h4><input type="text" name="UserData[]" value="'.$UserData[0].'"><br/>
              <h4>Subtitle: </h4><input type="text" name="UserData[]" value="'.$UserData[1].'"><br/>
              <h4>Footer: </h4><input type="text" name="UserData[]" value="'.$UserData[2].'"><br/>
              <input type="submit" value="Save" name="datasave" id="save">
         </form>';
} else {
    die("Error: {$con->errno} : {$con->error}");
}
if(isset($_POST['datasave']))
{
    $data = json_encode($_POST['UserData']);
    $query = "UPDATE users 
    SET UserData = '$data' WHERE Username = '$Username'";
    mysqli_query($con, $query);

    if (mysqli_query($con, $query)) {
        header("Location: edit.php");   
    } else {
        echo "Error updating record: " . mysqli_error($con);
    }
}

if ( $con->connect_error ) {
    die( 'Connect Error: ' . $con->connect_errno . ': ' . $con->connect_error );
}  
$con->close();
?>

Questions first: 首先提问:

  • Where does $Username variable coming from? $Username变量来自哪里?

  • Do you really intend to store an array to your users.UserData column? 您是否真的打算将数组存储到users.UserData列?

If you want to continue this schema of yours, you have to figure out how to store them to your database. 如果要继续使用您的这种模式,则必须弄清楚如何将它们存储到数据库中。 You will encounter an error if you try to use *_real_escape_string() if you use it in an array. 如果在数组中使用*_real_escape_string()会遇到错误。 Second parameter will be looking for strings, not for an array. 第二个参数将查找字符串,而不是数组。

You can try to run them all and then use *_real_escape_string and then restore them. 您可以尝试全部运行它们,然后使用*_real_escape_string ,然后将其还原。

for($x = 0; $x < count($_POST["UserData"]); $x++){

  $data[$x] = mysqli_real_escape_string($con, $data[$x]);

}

Did you properly concatenate the variable to your HTML form? 您是否将变量正确连接到HTML表单?

echo '<form action="edit.php" method="POST" id="content">
          <h3>Homepage</h3>
          <hr/>
          <h4>Title: </h4><input type="text" name="UserData[]" value="'.$UserData[0].'"><br/>
          <h4>Subtitle: </h4><input type="text" name="UserData[]" value="'.$UserData[1].'"><br/>
          <h4>Footer: </h4><input type="text" name="UserData[]" value="'.$UserData[2].'"><br/>
          <input type="submit" value="Save" name="datasave" id="save">
     </form>';

@ChrisBaker covers the rest of storing and retrieving the data from your database. @ChrisBaker涵盖了存储和检索数据库数据的其余部分。


Standard way of storing Data 标准的数据存储方式

But the advisable way to store such data in your database is to restructure your table in your database. 但是,将此类数据存储在数据库中的明智方法是在数据库中重组表。 Separate each into their own column: 将每个单独的列:

Your users table will look like: 您的users表如下所示:

id |  Username   |   title   | subtitle  | footer  |
---+-------------+-----------+-----------+---------+
 1 | LankyMoose  |    OP     |  English  | sticky  |
 2 | Chris Baker | Boy Scout |  English  | dynamic |
 3 | Logan Wayne |   Whiner  |   Multi   |  none   |

So you can store them to your database and fetch them easier. 因此,您可以将它们存储到数据库中,并更轻松地获取它们。


Dynamic Storing of Data 动态存储数据

But what if those fields are dynamic? 但是,如果这些字段是动态的呢? You want to store more data from the user ( that is what I thought of when you try to insert an array of data from the user ). 您想存储来自用户的更多数据( 这是我尝试插入来自用户的数据数组时所想到的 )。

You can create extra tables that stores the different types of data from the user and stores the user's input. 您可以创建额外的表,用于存储来自用户的不同类型的数据并存储用户的输入。 Lets name the first table for example, data_table : 让我们命名第一个表,例如data_table

 data_id | data_type
---------+-----------
    1    |   Title
    2    |   Subtitle
    3    |   Footer

Then for the second table which stores the users input, lets name it data_input : 然后,对于存储用户输入的第二个表,将其命名为data_input

input_id | data_id | user_id | user_input
---------+---------+---------+------------
    1    |    1    |    1    |     OP
    2    |    2    |    1    |   English
    3    |    3    |    1    |    sticky
    4    |    1    |    2    |  Boy Scout
    5    |    2    |    2    |   English
    6    |    3    |    2    |   dynamic
    7    |    1    |    3    |   Whiner
    8    |    2    |    3    |   Multi
    9    |    3    |    3    |    none

Your users table would look like this now: 您的users表现在看起来像这样:

user_id |   username    
--------+-------------
   1    |  LankyMoose
   2    |  Chris Baker
   3    |  Logan Wayne

So for example, you want to get data from LankyMoose , you can try this query: 因此,例如,您想从LankyMoose获取数据,可以尝试以下查询:

SELECT a.username,
       c.data_type,
       b.user_input
FROM users a
     LEFT JOIN data_input b ON a.user_id = b.user_id
     LEFT JOIN data_table c ON b.data_id = c.data_id
WHERE user_id = 1

Result will be: 结果将是:

  username  | data_type | user_input
------------+-----------+------------
 LankyMoose |   Title   |    OP
 LankyMoose |  Subtitle |  English
 LankyMoose |   Footer  |   sticky

With this method, you can add more fields just by inserting data to data_table . 使用此方法,只需将数据插入data_table即可添加更多字段。


I would also suggest that you use prepared statement since you are already using mysqli_* extension. 我还建议您使用prepared statement因为您已经在使用mysqli_*扩展名。

The first and most obvious answer is more of a question: why store them all in one database column? 第一个也是最明显的答案是一个问题:为什么将它们全部存储在一个数据库列中? You may have your reasons, but examine them again, this is not standard. 您可能有自己的原因,但请再次检查,这不是标准的。 One would typically have a database table with specific fields for each value. 通常会有一个数据库表,其中包含每个值的特定字段。

Assuming it isn't possible or practical to use multiple fields, you cannot simply toss a PHP array into the database and get it out later. 假设无法使用多个字段或不切实际,则不能简单地将一个PHP数组放入数据库中并在以后取出它。 Using mysqli_escape_string is not doing what you expect -- as the name implies, it wants a string and you're giving it an array. 使用mysqli_escape_string并没有达到您的期望-顾名思义,它需要一个字符串,而您mysqli_escape_string它一个数组。 You must convert the PHP scalar array into something the database can work with, most likely a string. 您必须将PHP标量数组转换为数据库可以使用的东西,很可能是字符串。 You have a few options there. 您在那里有一些选择。 You can use serialize , or json_encode . 您可以使用serializejson_encode Of the two, I suggest JSON. 在这两者中,我建议使用JSON。

If you encode the array to a string, you will of course have to convert it BACK to a value PHP can work with, you have to decode it. 如果将数组编码为字符串,则当然必须将其转换回PHP可以使用的值,并且必须对其进行解码

To encode to JSON: 编码为JSON:

$data = json_encode($_POST['UserData']);

... and to decode: ...并进行解码:

$UserData = json_decode($row['UserData'], true);

You can also dispense with the numerically indexed items by crafting your fields as follows: 您还可以通过如下制作字段来省去数字索引项:

<input type="text" name="UserData[title]" value=<?=($UserData['title'])?>>

I would be remiss if I did not mention that you should switch to parameterized queries, otherwise you are open for an SQL injection attack. 如果我没有提到您应该切换到参数化查询,那我会很失落,否则您很容易受到SQL注入攻击的影响。 See more: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php -- manual escaping with mysqli_escape_string is cumbersome and one is apt to neglect to escape everything correctly. 查看更多: http : mysqli_escape_string -使用mysqli_escape_string手动转义很麻烦,并且容易忽略以正确地转义所有内容。

Your query and use of a while loop leaves open the possibility that more than one user with the given username will be found. 您的查询和使用while循环使您有可能找到多个具有给定用户名的用户。 The while loop will go through these, until the last one, then proceed to your form. while循环将遍历这些循环,直到最后一个循环,然后进入表单。 If it is fair to say that you will only get one row back, only one user will have the given username, dispense with the while loop and simply fetch the data one time. 公平地说,您只会返回一行,只有一个用户将具有给定的用户名,省去了while循环,并且只需一次获取数据。 You may also want to put a LIMIT 1 restriction on the query, and put a unique index on the column in the database. 您可能还希望对查询设置LIMIT 1限制, 在数据库的列上设置唯一索引。

Documentation/Further Reading 文档/进一步阅读

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM