2017-10-12 61 views
2

我有一个html格式作为index.php和另一个mydata.php文件。我想将数据放入mydata.php文件,但有一些问题如何将值添加到数组php文件当html表单提交在PHP中?

的index.php

<form action="" method="POST"> 
    <input name="field1" type="text" /> 
    <input name="field2" type="text" /> 
    <input type="submit" name="submit" value="Save Data"> 
</form> 

<?php 
if (isset($_POST['field1']) && isset($_POST['field2'])) { 
    if (!filesize('mydata.php')) { 
     $data0 = '<?php $a = array(' . "\n"; 
     $ret = file_put_contents('mydata.php', $data0, FILE_APPEND | LOCK_EX); 
    } 

    $data = '"' . $_POST['field1'] . '"' . '=>' . '"' . $_POST['field2'] . '",' . "\n"; 
    $ret = file_put_contents('mydata.php', $data, FILE_APPEND | LOCK_EX); 

    if ($ret === false) { 
     die('There was an error writing this file'); 
    } else { 
     echo "$ret bytes written to file"; 
    } 
} 
?> 

mydata.php

$array = array("a"=>"b"); 

当我添加提交新的价值,我想需要像我的发布数据推新阵列

Array 
(
    [field1] => c 
    [field2] => d 
    [submit] => Save Data 
) 

$array = array("a"=>"b","c"=>"d"); 
+0

你可以做这样的:'$数据[$ _ POST [ '字段1'] = $ _ POST [ '字段2']' – Saani

+0

为什么你不使用DB (MySQL或SQLite)?如果你想将数据存储在一个文件中,那么我建议你使用JSON。 – Neodan

+0

@Saani OP想要将数据添加(存储)到'mydata.php'文件中。 – Neodan

回答

2

你只需将数据添加到$array,生成的PHP代码,然后将其保存到文件。

例如用PHP文件:

<?php 
// data for the form ($_POST), all data from the client (browser) MUST be validated and sanitized 
$formData = [ 
    'field1' => 'c', 
    'field2' => 'd' 
]; 

// load mydata.php if it was not loaded before 
require_once 'mydata.php'; 

// add new data or update existen 
$array = array_merge($array, $formData); 
$tab = ' '; 

// generate the new content for the mydata.php file 
$newContent = '<?php' . PHP_EOL . '$array = [' . PHP_EOL; 
foreach ($array as $key => $value) 
    $newContent .= $tab . "'$key' => '" . addslashes($value) . "'," . PHP_EOL; 

$newContent .= '];' . PHP_EOL; 

//save the new content into file 
file_put_contents('mydata.php', $newContent); 

但我真的建议您使用JSON文件为。

例如使用JSON文件:

<?php 
// data for the form ($_POST), all data from the client (browser) MUST be validated and sanitized 
$formData = [ 
    'field2' => 'c', 
    'field3' => 'd' 
]; 

$array = []; 

// load data 
if (file_exists('mydata.json')) 
    $array = json_decode(file_get_contents('mydata.json'), true); 

// add new data or update the existen 
$array = array_merge($array, $formData); 

// save the new data into file 
file_put_contents('mydata.json', json_encode($array), LOCK_EX); 
+0

感谢您的回答neodan –

+0

其工作正常 –

+0

@DivyeshSigmate不要忘记标记答案,因为在其他方面,这个问题将来没用了。 – Neodan

1

我不确定你在问什么,因为问题不清楚,但如果我得到它的权利,以添加新键值对添加到现有阵列,你可以尝试

$field1 = $_POST['field1']; // $field1 = "c" 
$field2 = $_POST['field2']; // $field2 = "d" 

$array[$field1] = $field2;