Divyesh Sigmate
Divyesh Sigmate

Reputation: 97

How to add value into array php file When html form submit in php?

I have one html form as index.php and also another mydata.php file. I want to put data into mydata.php file, but there is some issue

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");

When I add submit new value i want to need push new array like my post data

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

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

Upvotes: 2

Views: 1336

Answers (2)

Neodan
Neodan

Reputation: 5252

You just need to add data to $array, generate the PHP code and then save it into file.

Example with PHP file:

<?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);

But I really recommend to you use the JSON file for that.

Example with JSON file:

<?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);

Upvotes: 2

Aesreal
Aesreal

Reputation: 131

I'm not sure what you are asking because the question is not clear, but if I am getting it right, to add add a new key-value pair to your existing array, you could try

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

$array[$field1] = $field2;

Upvotes: 1

Related Questions