大家好,我得到阵列后,如何将数组存储在数据库中 编码
if (isset($_POST['submit'])) {
$data_t1 = $_POST['t1'];
foreach ($data_t1 as $key => $value) {
echo 'T1: ' . $value . '<br />';
echo 'T2: ' . $_POST['t2'][$key] . '<br />';
echo 'T3: ' . $_POST['a1'][$key] . '<br />';
echo 'Username: ' . $_POST['username'][$key] . '<br /><br />';
echo 'T11: ' . $_POST['t11'] . '<br />';
echo 'T22: ' . $_POST['t22'][$key] . '<br />';
echo 'T33: ' . $_POST['a11'][$key] . '<br />';
echo 'name: ' . $_POST['name'][$key] . '<br /><br />';
}
$data_t2 = $_POST['t2'];
$data_t3=$_POST['a1'];
$data_t4=$_POST['username'];
$data_t11 = $_POST['t11'];
$data_t22=$_POST['t22'];
$data_t33=$_POST['a11'];
$data_t44=$_POST['name'];
}
var_dump($data_t1);
var_dump($data_t2);
var_dump($data_t3);
var_dump($data_t4);
var_dump($data_t11);
var_dump($data_t22);
var_dump($data_t33);
var_dump($data_t44);
?>
数组以表格形式显示
$data_t1( 12 12)
$data_t2( 4 3)
$data_t3( 5 6)
$data_t4( 1.44 1.33)
$data_t11( 12 12)
$data_t22( 4 3)
$data_t33( 5 6)
$data_t44( 1.44 1.33)
我需要以表格
将数据存储在数据库中row1 12 4 5 1.44 12 4 5 1.44
row2 12 3 6 1.33 12 3 6 1.33
我编辑了我的问题
答案 0 :(得分:1)
这是一个符合你想要的代码片段:
//database connection
$db = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
//query
$sql = "INSERT INTO table (c1, c2, c3, c4) VALUES (:c1, :c2, :c3, :c4)";
$stmt = $db->prepare($sql);
$stmt->execute(array(
':c1'=>$data_t1[0],
':c2'=>$data_t2[0],
':c3'=>$data_t3[0],
':c4'=>$data_t4[0],
));
//this is for row1:
+--------------------+
| 12 | 4 | 6 | 1.33 |
+--------------------+
+++++++++++++++++++++++++++++++++++++++++
//and for row2
$stmt->execute(array(
':c1'=>$data_t1[1],
':c2'=>$data_t2[1],
':c3'=>$data_t3[1],
':c4'=>$data_t4[1],
));
//this is for row2:
+----------------------+
| 12 | 3 | 5 | 1.44 |
+----------------------+
NB:我没有对此代码进行测试运行,因此您可能会遇到一些错误。
修改强>
使用Barmar的想法只需添加额外的列c5, c6, c7, c8
并将其绑定到新值$data_t11[$i], $data_t22[$i], $data_t33[$i], $data_t44[$i]
$sql = "INSERT INTO table (c1, c2, c3, c4, c5, c6, c7, c8) VALUES (:c1, :c2, :c3, :c4, :c5, :c6, :c7, :c8)";
$stmt = $db->prepare($sql);
foreach ($data_t1 as $i => $value) {
$stmt->execute(array(
':c1'=>$data_t1[$i],
':c2'=>$data_t2[$i],
':c3'=>$data_t3[$i],
':c4'=>$data_t4[$i],
':c5'=>$data_t11[$i],
':c6'=>$data_t22[$i],
':c7'=>$data_t33[$i],
':c8'=>$data_t44[$i],
));
}
答案 1 :(得分:1)
这就像Tifa的答案,但使用for
循环,因此它可以使用任意数量的值。
$db = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
//query
$sql = "INSERT INTO table (c1, c2, c3, c4) VALUES (:c1, :c2, :c3, :c4)";
$stmt = $db->prepare($sql);
foreach ($data_t1 as $i => $value) {
$stmt->execute(array(
':c1'=>$data_t1[$i],
':c2'=>$data_t2[$i],
':c3'=>$data_t3[$i],
':c4'=>$data_t4[$i],
));
}