Submitting HTML Form data in JSON File (without MySql Database) in PHP
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>PHP & JSON File</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="main">
<div id="header">
<h1>Save Form Data in JSON File</h1>
</div>
<div id="table-data">
<form id="submit_form" method="post" action="save-form.php">
<table width="100%" cellpadding="10px">
<tr>
<td width="150px"><label>Name</label></td>
<td><input type="text" name="fullname" autocomplete="off" placeholder="Enter name"></td>
</tr>
<tr>
<td><label>Age</label></td>
<td><input type="number" name="age" autocomplete="off" placeholder="Enter age"></td>
</tr>
<tr>
<td><label>City</label></td>
<td>
<input type="text" name="city" autocomplete="off" placeholder="Enter city name">
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="submit" id="submit" value="Save">
</td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
Above File is index.php File
Below is save-form.php File
<?php
if ($_POST["fullname"] != "" && $_POST["age"] != "" && $_POST["city"] != "") {
if (file_exists("json/student_data.json")) {
$current_data = file_get_contents("json/student_data.json");
$array_data = json_decode($current_data, true);
$new_data = array(
"name" => $_POST["fullname"],
"age" => $_POST["age"],
"city" => $_POST["city"]
);
$array_data[] = $new_data;
$json_data = json_encode($array_data, JSON_PRETTY_PRINT);
if (file_put_contents("json/student_data.json", $json_data)) {
echo "<h3>Successfully saved data in JSON File.</h3>";
} else {
echo "<h3>Unsuccessfully saved data in JSON File.</h3>";
}
} else {
echo "<h3>JSON File not exist.</h3>";
}
} else {
echo "<h3>All form fields are required.</h3>";
}
Below is css/style.css File.
body {
font-family: arial;
background-color: #b2bec3;
padding: 0;
margin: 0;
}
#main {
background-color: #ffffff;
width: 700px;
margin: 20px auto;
font-size: 15px;
}
h1 {
text-align: center;
font-size: 40px;
margin: 0;
}
#header {
background-color: #6c5ce7;
color: #ffffff;
height: 50px;
padding: 15px;
}
#table-data {
padding: 15px;
min-height: 500px;
}
table tr td:first-child {
text-align: right;
font-weight: bold;
}
input[type="text"],
input[type="number"] {
height: 25px;
width: 200px;
font-size: 17px;
}
input[type="submit"] {
background: #6c5ce7;
color: #ffffff;
border: 0;
border-radius: 3px;
padding: 5px 10px;
outline: 0;
cursor: pointer;
height: 35px;
width: 100px;
font-size: 20px;
}
Below is student_data.json File where Form data will be saved.
Comments
Post a Comment