[英]How to save each data from an array to the database
I have a form where I needed to split into two table in the database. 我有一个需要在数据库中拆分成两个表的表单。 tbl_1
consist of single value per column, then tbl_2
consist of multiple value per column. tbl_1
每列包含一个值,然后tbl_2
每列包含多个值。 I know if I pass multiple data per column I'm going to violate a normalization in database. 我知道如果我每列传递多个数据,则会违反数据库中的规范化。 So what I did I reference tbl_1
to tbl_2
. 所以我做了什么我引用tbl_1
到tbl_2
。 The problem is I don't know how to save each value in an array to a column. 问题是我不知道如何将数组中的每个值保存到列中。 example Classification has 4 value which I needed to save in tbl_2
and reference it to tbl_1
. 示例分类具有4个值,我需要将其保存在tbl_2
并将其引用到tbl_1
。 How am I able to do this? 我该怎么做? I'm using PDO
. 我正在使用PDO
。
HTML snippet: HTML片段:
<input type="text" name="classification[]" placeholder="Classification No. 1" />
<input type="text" name="classification[]" placeholder="Classification No. 2" />
<input type="text" name="classification[]" placeholder="Classification No. 3" />
<input type="text" name="classification[]" placeholder="Classification No. 4" />
So for each value will create 4 rows that has the same id being reference to tbl_1
. 因此,将为每个值创建4行,这些行具有引用给tbl_1
的相同ID。 It should be like this: 应该是这样的:
I am just giving demo....try something like this 我只是给演示...。尝试这样的事情
<?php
$x = 1;
$y = 1;
$classification = array('class1', 'class2');
$area = array('area1', 'area2');
$market = array('market1', 'market2');
$no_of_loop = count($classification); //4
while($no_of_loop)
{
$query = insert into (`tbl_1_id`, `tbl_2_id`, `Classification`, `Area`, `Market`) values($x, $y, $classification, $area, $market);
$x++;
}
$y++;
mysqli_query($query, $con);
?>
Try multidimensional array instead. 请尝试使用多维数组 。
So, you input
can be something like: 因此,您input
可能类似于:
<input type="text" name="data[classification][]" placeholder="Classification No. 1" />
<input type="text" name="data[area][]" placeholder="Area No. 1" />
<input type="text" name="data[market_value]" placeholder="Market Value No. 1" />
Then, using for
loop, you can insert
them to database
: 然后,使用for
循环,可以insert
它们insert
database
:
$data = 'your array here whatever you receive using GET/POST';
for($i=0; $i<count($data['classification']); $i++){
$sql = INSERT INTO (`tbl_1_id`, `tbl_2_id`, `classification`, `area`, `market_value`) VALUES (`auto_increment_id`, `value_of_table1`, $data['classification'][$i], $data['area'][$i], $data['market_value'][$i]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.