How to save input form data as an array in PHP - javascript

I have a form which takes a student name, subject and age. When submitted, it saves the data as an array in txt file. Next time, when I put new data and submit it, it creates a new array in that txt file instead of appending it to the previous array.
<?php
if(!empty($_GET)){
$student = [];
$student['name'] = $_GET['name'];
$student['subject'] = $_GET['subject'];
$student['age'] = $_GET['age'];
$studentArray = [];
array_push($studentArray, $student);
$str = print_r($studentArray, true);
file_put_contents('student.txt', $str, FILE_APPEND);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="" method="GET">
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<label for="name">Subject:</label>
<input type="text" name="subject" id="subject">
<label for="name">Age:</label>
<input type="number" name="age" id="age">
<input type="submit" name="submitButton">
</form>
</body>
</html>
output looks like this:
however I want to save it like below:
How could I do that?

If you really have to see your nice array in text use this:
if(!empty($_GET)){
$student = array();
$int = 0;
$txtfile = "student.txt";
if (file_exists($txtfile)) {
$fgc = file_get_contents($txtfile);
$expl = explode("[".$int."] => Array", $fgc);
while (count($expl) > 1) {
$expl2 = (count($expl) > 1) ? explode("[".($int+1)."] => Array", $expl[1])[0] : $expl[1];
$m = preg_match_all("#\\[([\d\w]+)\\] => ([^\n]*)#imus", $expl2, $matches);
if ($m == 0) { break; }
foreach ($matches[1] as $key => $val) {
$student[$int][$val] = $matches[2][$key];
}
$int++;
$expl = explode("[".$int."] => Array", $fgc);
}
}
$student[$int]['name'] = $_GET['name'];
$student[$int]['subject'] = $_GET['subject'];
$student[$int]['age'] = $_GET['age'];
$str = print_r($student, true);
file_put_contents('student.txt', $str);
print_r($student);
}
But please use a serialized version like this:
if(!empty($_GET)){
$student = array();
$int = 0;
$txtfile = "student.txt";
if (file_exists($txtfile)) {
$fgc = file_get_contents($txtfile);
$student = unserialize($fgc);
$int = count($student);
}
$student[$int]['name'] = $_GET['name'];
$student[$int]['subject'] = $_GET['subject'];
$student[$int]['age'] = $_GET['age'];
file_put_contents('student.txt', serialize($student));
print_r($student);
}
print_r for debug only.
Have fun ;)

You have to use JSON in order to update your array constantly.
the important point is you have to load your students in a variable and then push the new student to that variable so, in the end, you can save your students variable which contains all students in one array like you want.
Requirements to make this code works:
Create a file named student.json and put [] inside the file
Also, I highly suggest go and learn about JSON in PHP so you can have a better understanding of how this code is working now
if(!empty($_GET)){
$student = [];
$student['name'] = $_GET['name'];
$student['subject'] = $_GET['subject'];
$student['age'] = $_GET['age'];
$studentArray = json_decode( file_get_contents('student.json'), true);
array_push($studentArray, $student);
$str = print_r($studentArray, true);
file_put_contents('student.json', json_encode($studentArray));
}

Related

PHP Read file content based on pathname

UPDATED:
I am using RecursiveIteratorIterator to scan the directories to read index.html file.
Now, based on the Pubname and Pubversion, i am trying to read the corresponding index.html file, to get the values of Readability Grade, Readability Score etc. (by storing the values in local storage)
The values are fetched from local storage if i use the html and JS code separately, but after i integrate into php, it is not working.
Code:
<?php
//error_reporting(0);
//Get Pub version
function get_version($path){
$needle = "=";
if(($pos = strpos($path, $needle)) != 0){
$bits = str_split($path, $pos + strlen($needle));
$integer_count = 0;
for($x = 0; $x < strlen($bits[1]); $x++){
if(is_numeric($bits[1][$x])){
$integer_count++;
}else{
break;
}
}
if($integer_count > 0){
$bits = str_split($bits[1], $integer_count);
return $bits[0];
}
}
return -1;
}
$it = new RecursiveDirectoryIterator("C:\Users\Sachin_S2\Desktop\Script");
foreach(new RecursiveIteratorIterator($it,RecursiveIteratorIterator::SELF_FIRST) as $file) {
//IGNORE FILE TYPES
//$filetypes = array("jpg", "png", "pdf", "css", "csv","log","txt");
$htmlfiles = array("html");
$filetype = pathinfo($file, PATHINFO_EXTENSION);
if (in_array(strtolower($filetype), $htmlfiles)) {
// skip dot files while iterating
$it->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
$files = array($file);
$pathname = $file->getPathname();
print_r($pathname);
$version = get_version($pathname);
if($version > 0){
// use $version to read correct file
include 'html/home.html';
}
echo '*********************************************************************************'.'<br/><br/>';
}
}
html/home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>SEO Metrics</title>
</head>
<body>
<!--Begin script code-->
<form name="myform3">
<!--
<input type="hidden" name="formvar" value="">
<input type="file" name="file" id="file">
<p id="demo"></p><br/><br/>
-->
<div class="form-group">
<label>Readability Grade:</label>
<input type="text" class="form-control" id="grade">
</div>
<div class="form-group">
<label>Readability Score:</label>
<input type="text" class="form-control" id="score">
</div>
<div class="form-group">
<label>Total Word Count:</label>
<input type="text" class="form-control" id="words">
</div>
</form>
<!--END script code-->
<!--Custom JS code-->
<script src="js/home.js"></script>
</body>
</html>
js/home.js
$(document).ready(function() {
document.getElementById('file').onchange = function() {
const file = this.files[0];
const reader = new FileReader();
reader.onload = (event) => {
const file = event.target.result;
const allLines = file.split(/\r\n|\n/);
let arr = allLines;
arr.forEach((kv) => {
if (kv.includes("Flesh-Kincaid Grade Level")) {
var fetch_grade = kv.replace(/<\/?[^>]+(>|$)/g, "");
var formated_grade = fetch_grade.split(":").pop(); //Remove part of the string before ":"
localStorage.setItem("Readability_Grade", formated_grade);
document.getElementById('grade').value = localStorage.getItem("Readability_Grade").replace(/\s/g, ""); //Assign localStorage to text box
localStorage["Readability_Grade"] = grade.value;
//alert(formatedgrade);
}
if (kv.includes("Flesh Reading Ease Score")) {
var fetch_score = kv.replace(/<\/?[^>]+(>|$)/g, "");
var formated_score = fetch_score.split(":").pop();
localStorage.setItem('Readability_Score', formated_score);
document.getElementById('score').value = localStorage.getItem("Readability_Score").replace(/\s/g, "");
//alert(formatedscore);
}
if (kv.includes("Reuse Metrics Score")) {
var metricscore = kv;
//alert(metricscore);
}
if (kv.includes("Total words")) {
var totalwords = kv.replace(/<\/?[^>]+(>|$)/g, "");
var total_words_formated = totalwords.split(":").pop();
localStorage.setItem('Word_Count', total_words_formated);
document.getElementById('words').value = localStorage.getItem("Word_Count").replace(/\s/g, "");
//alert(totalwords);
}
});
};
reader.onerror = (event) => {
alert(event.target.error.name);
};
reader.readAsText(file);
};
});
Output:
On reading this php script, i should be able to read index html (for each file paths - based on pubname and version), and get the values of Readability_Grade and score etc., which i am not able to get.
Firstly get the version number from the string, below is a method to do just that.
function get_version($path){
$needle = "Pub=";
if(($pos = strpos($path, $needle)) != 0){
$bits = str_split($path, $pos + strlen($needle));
$integer_count = 0;
for($x = 0; $x < strlen($bits[1]); $x++){
if(is_numeric($bits[1][$x])){
$integer_count++;
}else{
break;
}
}
if($integer_count > 0){
$bits = str_split($bits[1], $integer_count);
return $bits[0];
}
}
return -1;
}
And then you can use it like this.
foreach ($paths as $path){
$version = get_version($path);
if($version > 0){
// use $version to read correct file
}
}
Thats if I undertoood your question.
Disclaimer: Quickly typed up but should work.

How to obtain values of dynamically created select dropdowns in php

I am trying to obtain the values of dynamically created select dropdowns from my php page. The dropdowns were added via javascript to the page.
The error that I get is Notice: Undefined index: daySelect in C:\wamp\www\responsive2\select.php on line 7
I would like to know how to access posted select dropdowns values with php.
Thanks in advance.
Code follows
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST"){
echo "We have something";
echo ($_POST['daySelect']); // error here
}
else
{
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dynamic Select</title>
</head>
<body>
<form id="theform" style="display: none" method="POST" name="theform" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div id="placeHere"></div>
<button type="submit">Submit</button>
</form>
<button onclick="createSelect()">Create</button>
<script>
var elem = document.getElementById('placeHere');
var daySelect = new Array();
var theForm = document.getElementById('theform');
var numSelects = 0;
var days = ['01','02','03','04','05','06','07','08','09','10',
'11','12','13','14','15','16','17','18','19','20',
'21','22','23','24','25','26','27','28','29','30',
'31'];
function createSelect()
{
numSelects++;
daySelect.push(document.createElement('select'));
daySelect[daySelect.length -1].setAttribute('id',
daySelect[daySelect.length -1]);
daySelect[daySelect.length -1].name = daySelect[daySelect.length -1];
var opt = document.createElement('option');
opt.text = "Select";
opt.value = "";
//myArray[myArray.length - 1];
daySelect[daySelect.length -1].appendChild(opt);
for (var i = 0; i < 31; i++)
{
var opt = document.createElement("option");
opt.text = days[i];
opt.value = days[i];
//opt.className = i;
//optarr.push(opt[i]);
daySelect[daySelect.length -1].appendChild(opt);
}
elem.appendChild(daySelect[daySelect.length -1]);
theForm.style.display = "block";
//alert("HI");
}
</script>
</body>
</html>
<?php
}
?>
You need to set your select "name" and "id" to a string name. Right now you are setting those 2 attributes to the daySelect object value, which is getting interpreted as a string, so you have:
<select id="[object HTMLSelectElement]" name="[object HTMLSelectElement]">
Update the the .setAttribute and .name lines to:
daySelect[daySelect.length - 1].setAttribute('id',
'daySelect' + (daySelect.length - 1));
daySelect[daySelect.length - 1].name = 'daySelect[]';
The name is set to an array because of the [], so you could just loop through $_POST['daySelect'], with PHP, using a foreach.
Change the echo to print_r to view array values in the browser.
Hope that helps.

PHP Javascript HTML

I'm having trouble finding my exact question so I'll post it here. I'm working with an oracle database and I'm linking it to an HTML website via javascript and php. I got the php file to display properly. Essentially what's supposed to happen is I have 4 button, each one generates a specific query and displays the results in a new html page. It's a movie database, so one of our queries is Budgets vs. Genre. It works the way I have it, but it doesn't generate it via the html file, it displays the PHP file. My goal is to retrieve the output of the PHP file via javascript and set it to the HTML file for output. I'm new to php and javascript working together, so maybe someone can tell me what's happening here and what needs to be changed for it to work properly. I got the javascript code from oracles website for connecting a database to a website.
Here's my PHP first:
<?php
// Connect to the database=
$c = oci_connect ("user101", "pass101", "localhost:1521/XE");
// Define the query.
$q = 'SELECT distinct m.title, f.budget FROM movies m, finance f WHERE m.imdb_id = f.imdb_id AND budget > 100000000 ORDER BY budget DESC';
// Parse the query.
$s = oci_parse($c, $q);
$didbv = 60;
oci_bind_by_name($s, ':budget', $budget);
oci_bind_by_name($s, ':title', $title);
// Execute the query.
oci_execute($s);
$i = 1;
print '<table border="1"><tr><th>Rank</th><th>Title</th><th>Budget</th>';
while (($row = oci_fetch_array($s, OCI_ASSOC)) != false) {
$table[i++] = array("title" => $row['TITLE'], 'budget' => $row['BUDGET']);
}
oci_free_statement($s);
// Close the connection.
oci_close($c);
header('Content-Type: application/json');
echo json_encode($table);
?>
and here's my javascript :
$(function() {
$("button#genBudg").click(function() {
$.getJSON("ajaxCopy.php", function(data) {
var reportTable = $("<table>", {
border: 1
});
reportTable.append("<thead><th>Rank</th><th>Title</th><th>Budget</th></thead><tbody></tbody>");
$.each(data, function(k, v) {
reportTable.find("tbody").append("<tr><td>" + k + "</td><td>" + v.title + "</td><td>" + v.budget + "</td></tr>");
});
$("#bud_gro").append(reportTable);
window.location.replace("generate_report.html");
});
});
});
and here's my html:
(select_report.html)
<html lang ="en">
<head>
<title>Movie Analysis</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/CSS" href="movies.CSS">
</head>
<body>
<h2>Reports</h2>
<div class="input_options">
<div>
<button type="button" class="option" style="padding:10px 30px" id="genBudg">Genre vs Budget</button>
<button type="button" class="option" style="padding:10px 30px">Rating vs Budget</button>
</div>
<div>
<button type="button" class="option" style="padding:10px 30px">Budget vs Gross</button>
<button type="button" class="option" style="padding:10px 30px">Actor vs Rating</button>
</div>
</div>
<script src ="jquery-1.4.4.js"></script>
<script src="movies.js"></script>
</body>
</html>
(generate_report.html)
<html lang ="en">
<head>
<title>Movie Analysis</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/CSS" href="movies.CSS">
</head>
<body>
<h2>Name of report</h2>
<div id = "bud_gro"></div>
<script src="movies.js"></script>
<script src="jquery-1.4.4.js"></script>
</body>
</html>
As discussed, it may be better to pass JSON data back to an AJAX call and build the table based on the results. This might look like this:
PHP
<?php
// Connect to the database= oci_connect ("user101", "pass101", "localhost:1521/XE");
// Define the query.
$q = 'SELECT distinct m.title, f.budget FROM movies m, finance f WHERE m.imdb_id = f.imdb_id AND budget > 100000000 ORDER BY budget DESC';
// Parse the query.
$s = oci_parse($c, $q);
$didbv = 60;
oci_bind_by_name($s, ':budget', $budget);
oci_bind_by_name($s, ':title', $title);
// Execute the query.
oci_execute($s);
$i = 1;
$table = array();
while (($row = oci_fetch_array($s, OCI_ASSOC)) != false) {
$table[i++] = array("title" => $row['TITLE'], "budget" => $row['BUDGET']);
}
oci_free_statement($s);
// Close the connection.
oci_close($c);
header('Content-Type: application/json');
echo json_encode($table);
?>
You can then make use of a jQuery solution like so:
HTML
<button id="getReport">
Get Report
</button>
<h2>Name of report</h2>
<p id="bud_gro"></p>
JavaScript
$(function() {
$("button#getReport").click(function() {
$.getJSON("ajax.php", function(data) {
var reportTable = $("<table>", {
border: 1
});
reportTable.append("<thead><th>Rank</th><th>Title</th><th>Budget</th></thead><tbody></tbody>");
$.each(data, function(k, v) {
reportTable.find("tbody").append("<tr><td>" + k + "</td><td>" + v.title + "</td><td>" + v.budget + "</td></tr>");
});
$("#bud_gro").append(reportTable);
});
});
});

Store a string in local storage

First of all,i'm sorry for my english. I've created a simple wishlist system for an online store i'm building using jquery. But now i don't know how to store the items in local storage so the user can see them the next time he visit the store. I'm new to jquery and my coding abilities are very poor. Here's what i built:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<style>
body{background:#333;font-family:"Open sans", sans-serif;font-size:100%;text-align:center;font-size:62.5%;}
button{padding:5px 20px;border-radius:4px;margin:10px auto;border:0;background-color:#fff;font-weight:600;cursor:pointer;color:#c12267;}
#wish_list{margin:100px auto;min-height:300px;width:100%;background:#fff;}
#wish_list .wish_list_heading{margin:0;color:#fff;height:30px;background-color:#c12267;overflow:hidden;padding:5px;font-weight:600;}
#wish_list_item{width:100%;text-align:center;border-spacing:0px;border-collapse:separate;}
.wishlist-item{position:relative;clear:both;width:100%;margin:2px 0;padding:0;float:left;display:block;height:80px;border-bottom:1px solid #EEE;}
.w-premove{position:absolute;width:20px;display:block;height:20px;top:30px;left:0;text-align:center;font-weight:900;font-size:140%;line-height:20px;color:red;}
.w-pimage{top:0;left:25px;width:75px;height:25px;display:block;position:absolute;}
.w-pimage img{width:100%;}
.w-pname{top:5px;left:100px;width:calc(100% - 100px);width:-o-calc(100% - 100px);width:-webkit-calc(100% - 100px);width:-moz-calc(100% - 100px);height:40px;padding:0;text-align:left;font-size:140%;font-weight:600;line-height:1em;position:absolute;}
.w-pname a{text-decoration:none;color:#333;}
.w-price{top:50px;left:100px;height:20px;width:75px;color:#c12267;font-weight:600;font-size:150%;text-align:center;line-height:20px;display:block;position:absolute;}
</style>
</head>
<body>
<button class='wishlist' product_name='Product 1' product_id='product1' product_link="PRODUCT PAGE URL" product_price='90' product_image="IMAGE LINK">DESEJAR</button>
<div id='wish_list'>
<p class="wish_list_heading">
<span id='listitem'>0</span>
<span id='p_label'>Product</span>
</p>
<table id='wish_list_item' border='0'></table>
</div>
<script type='text/javascript'>
var wish_list = new Array();
jQuery(function(){
jQuery(".wishlist").on("click",function(){
$data = "";
$product_id = jQuery(this).attr("product_id");
$product_name = jQuery(this).attr("product_name");
$prduct_price = jQuery(this).attr("product_price");
$product_link = jQuery(this).attr("product_link");
$product_image = jQuery(this).attr("product_image");
if(jQuery.inArray($product_id,wish_list)==-1){
$product_str = "<tr class='wishlist-item' id='list_id_"+$product_id+"'><td class='w-premove' wpid='"+$product_id+"'>x</td><td class='w-pimage'><img src='"+$product_image+"' /></td><td class='w-pname'><a href='"+$product_link+"'>"+$product_name+"</a></td><td class='w-price'>"+$prduct_price+"€</td></tr>";
jQuery("#wish_list_item").append($product_str);
wish_list.push($product_id);
}
count_items_in_wishlist_update();
});
jQuery("#wish_list_item").on("click",".w-premove",function(){
$product_id = jQuery(this).attr("wpid");
jQuery("#list_id_"+$product_id).remove();
wish_list = jQuery.grep( wish_list, function( n, i ) {
return n != $product_id;
});
count_items_in_wishlist_update();
});
});
function count_items_in_wishlist_update(){
jQuery("#listitem").html(wish_list.length);
if(wish_list.length>1){
jQuery("#p_label").html("Products");
}else{
jQuery("#p_label").html("Product");
}
}
</script>
</body>
</html>`
Is it possible to store the strings $product_str in local Storage and present them when the user comes back? How can this be done?
Use
localStorage.setItem("lastname", "Smith");
to set a value with lastname as key and "Smith" as value
Use,
var result = localStorage.getItem("lastname");
to get the value of key lastname
The localStorage object stores the data with no expiration date.
You might want to look into cookies.

User input stored in array using JavaScript

Hi guys i'm kinda new to javascript and for a while now, i've been struggeling with something that shouldnt be that hard. The thing that i'm trying to execute is to get user input stored in an array, and then get it to print the collected info into a specific div (later on i'm gonna try to create a table using the DOM and store the input there). But i cant get it to work, below is my code :) any suggestions?
JavaScript
function submitInfo(){
var nameInput = document.getElementById("name").value;
var ageInput = document.getElementById("age").value;
var fsInput = document.getElementById("fightingStyle").value;
var weightInput = document.getElementById("weight").value;
myArray[0]=nameInput;
myArray[1]=ageInput;
myArray[2]=fsInput;
myArray[3]=weightInput;
for(var i = 0; i<myArray.lenght; i++){
document.getElementById("theResult").innerHTML=myArray[i];
}
}
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="inl2a.css" />
<script type="text/javascript" src="inl2a.js"></script>
<title>Inlämning 2a</title>
</head>
<body>
<div id="inputFields">
<h3>Submit your fighters information:</h3>
Name:<br><br>
<input id="name" type="text" /><br><br>
Age:<br><br>
<input id="age" type="text" /><br><br>
Fighting style:<br><br>
<input id="fightingStyle" type="text" /><br><br>
Weight:<br><br>
<input id="weight" type="text" /><br><br>
<input id="button" value="Submit" type="button" onclick="submitInfo();" /><br><br>
</div>
<div id="theResult">
</div>
</body>
</html>
function submitInfo(){
var myArray = []; // problem 1
var nameInput = document.getElementById("name").value;
var ageInput = document.getElementById("age").value;
var fsInput = document.getElementById("fightingStyle").value;
var weightInput = document.getElementById("weight").value;
myArray[0]=nameInput;
myArray[1]=ageInput;
myArray[2]=fsInput;
myArray[3]=weightInput;
for(var i = 0; i<myArray.length; i++){ // problem 3
document.getElementById("theResult").innerHTML+=myArray[i]; // problem 2
}
}
you haven't initialized the array anywhere
you overwrite the innerHTML property so only the last value remains
you have a typo: lenght instead of length
You can also set the values directly in the array and no longer use the intermediary variables. Also, you can get theResult element once, outside of the loop:
function submitInfo(){
var myArray = []; // problem 1
myArray.push(document.getElementById("name").value);
myArray.push(document.getElementById("age").value);
myArray.push(document.getElementById("fightingStyle").value);
myArray.push(document.getElementById("weight").value);
var element = document.getElementById("theResult");
for(var i = 0; i<myArray.length; i++){
element.innerHTML += myArray[i]; // problem 2
}
}
suppose user inputs are title and name, then
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
You could put all of these in one array:
var m = [ title, name ];
then for title use,
document.getElementById(your_divID).innerText=m[0];
you can use textContent instead of innerText for mozilla support.

Categories

Resources