繁体   English   中英

将值存储为关联数组

[英]Storing values as an associative array

我有以下选择值:

<select name="vibe_quiz_tags[]" id="vibe_quiz_tags" multiple="" class="chzn-select chosen select2-hidden-accessible" tabindex="-1" aria-hidden="true">
   <option value="">Select Taxonomy</option>
   <option value="4">Test1</option>
   <option value="5">Test2</option>
</select>

如果同时选择了这两个值,则这些值将存储在我的数据库中,如下所示:

a:2:{i:0;s:1:"4";i:1;s:1:"5";}

发布此表单时,我将如何分配它们以在数据库中获得相同的输入?

为了安全地将其保存到数据库中,您首先要清理输入,然后使用准备好的语句将其插入数据库中。 就像是:

 //Always sanitize first:
 foreach($_POST['vibe_quiz_tags'] as $val)
 {
   if(!($val == 4 || $val == 5 || $val === ''))
   {
     die('User attempted to game the system, or submitted invalid input.');
   } 
 }

 // Serialize the data. This will get the format you have in the question.
 $todb = serialize($_POST['vibe_quiz_tags']);

 $db = new mysqli(/* Your database parameters here*/);

 // Replace table and field with the correct table and field
 // Prepare the statement
 $stmnt = $db->prepare('insert into table (field) values (?)')
          or die('Database error: ' . $db->error);
 // Bind the parameter to be a string. Passing the serialized value.
 $stmnt->bind_param('s',$todb) or die('Database error: ' . $db->error);
 //Execute the statement.
 $stmnt->execute() or die('Database error: ' . $stmnt->error);
 // Close the statement.
 $stmnt->close();
 // Close the database connection.
 $db->close();

暂无
暂无

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

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