Adding arrays inside an array from input PHP - php

My goal: I wanted to make a list system that stores an array that has 3 values...
"Product's Name",
"Product's Price",
"Amount of Products".
And I want the user to keep adding products and be able sum it all up by multiplying the price by products and summing it all together if there's two or more products in the array.
Expectations:
"Milk",
2.99,
40
"Apples",
3.00,
5
My problem is the array input is replacing index 0.
Result:
Milk
2.99
40
I tried adding the other value, it replaces index 0.
I need some help to understand this problem.
<html>
<body>
<input id="inventory" name="p-name" type="text" placeholder="product name">
<input id="inventory" name="p-price" type="text" placeholder="product name">
<input id="inventory" name="p-amount" type="text" placeholder="product name">
<input id="inventory" name="s-name" type="text" placeholder="product name">
<input id="inventory" name="s-price" type="text" placeholder="product name">
<input id="inventory" name="s-amount" type="text" placeholder="product name">
<input type=submit name=submit[AddToList] value='Add to list'>
<input type=submit name=submit[ClearAllList] value='Clear All List'>
<?php
$listOfInventories = array();
if (isset($_POST["submit"])) { // Checks if user clicked btn.
$sub = $_POST["submit"];
$time = $_POST["time"];
$pName = $_POST["p-name"];
$pPrice = $_POST["p-price"];
$AmountOfProducts = $_POST["p-amount"];
$sName = $_POST["s-name"];
$sPrice = $_POST["s-price"];
$TimesWorkersLabored = $_POST["s-amount"];
if (isset($sub["AddToList"])) {
echo " Added to list <br>";
array_push($listOfInventories, array($pName, $pPrice, $AmountOfProducts)) ;
foreach ($listOfInventories as $value) {
foreach ($value as $x) {
echo $x;
}
}
echo count($listOfInventories);
// Save something;
} elseif (isset($sub["ClearAllList"])) {
$listOfInventories = [];
// Delete something
}
?>
</body>
</html>
Adding first product
Adding second product
Edit1: Possibly the fault is the initialization array, but where should I put it? It might not work before the array_push.

Please use SESSION to do what you want (this is a rather standard way to handle things like "shopping cart")
Hence, try something like $_SESSION["listOfInventories"] = array(); and then array_push($_SESSION["listOfInventories"], array("Apple", 10.5, 1)) ;
Please try to run the following PHP script, and RELOAD to see the effect - it will preserve the data and add more item(s)
<?php
session_start();
if (!isset($_SESSION["listOfInventories"]))
{$_SESSION["listOfInventories"] = array();}
array_push($_SESSION["listOfInventories"], array("Apple", 10.5, 1)) ;
echo count($_SESSION["listOfInventories"]);
echo "....<br>";
array_push($_SESSION["listOfInventories"], array("Orange", 10.5, 1)) ;
echo count($_SESSION["listOfInventories"]);
echo "....<br>";
?>

Use method="POST", put your Type="submit" attribute to Submit in Double Quote and Value="".. also put your } at the end of the if statement, add session_start() into the Login file and call only the number of inputs in the Field. use Localhost to store your Timestamp.

Related

How do appending to associative array with variables work

i'm doing this exercise to understand te concepts and syntax of php.The error i get is that the array is not being appended by a new entry from a text box, if i hard code the values the program works fine and prints the array values. but as soon as i put the variable it just assign a new value to the [0] index.
here is the code:
<label for="Name">Student Name:
<input type="text" name="StdName" placeholder="Your name">
</label>
<label for="Name">Grade:
<input type="text" name="StdGrade" placeholder="Your Grade">
</label>
<input type="submit" name="submit"value="submit">
</form>
<?php
// Associative array new
$studentName = $_POST['StdName'];
$studentGrade = $_POST['StdGrade'];
$classGrades = Array();
$classGrades['name'][] = $studentName;
$classGrades['grade'][] = $studentGrade;
echo "<br> <br> Your name is: $studentName and your grade is: $studentGrade <br> <br>";
foreach($classGrades as $key=>$value){
echo join($value,' <br>');
}
?>```
Your loop is wrong. You have separate name and grade arrays, so that's what you need to loop over:
foreach ($classGrades['name'] as $index => $name) {
$grade = $classGrades['name'][$index];
echo "$name<br>$grade<br>";
}
But it would be better if you didn't create separate array and kept the name and grade together in a single associative array:
$classGrades[] = ['name' => $studentName, 'grade' => $studentGrade];
Then your loop would look like:
foreach ($classGrades as $grade) {
echo $grade['name'] . "<br>" . $grade['grade'] . "<br>";
}
If you want the variable to persist between form submissions, you need to use a session variable.
Put
<?php
session_start();
at the beginning of the script. Then use $_SESSION['classGrades'] instead of $classGrades, and initialize it like this:
if (!isset($_SESSION['classGrades'])) {
$_SESSION['classGrades'] = array();
}
Basically you need to store your values, in some database.
Here is a simple start using a json file named students.json as database. That file will be created along your php file in the same folder, if not existing.
First you was missing the form elements and the method (by default it uses GET, thus this was not working).
Testing with isset() avoids populating the database with empty values, at page load or refreshs.
This is not very secure as such, you will have to work on that later on. Hint: What if a user insert a quote ' or " in his name?
<form method="post">
<label for="Name">Student Name:
<input type="text" name="StdName" placeholder="Your name">
</label>
<label for="Name">Grade:
<input type="text" name="StdGrade" placeholder="Your Grade">
</label>
<input type="submit" name="submit"value="submit">
</form>
<?php
if (!is_file("students.json")){
file_put_contents("students.json", json_encode([]) );
}
$classGrades = json_decode(file_get_contents("students.json"),true);
if (isset($_POST['StdName']) && isset($_POST['StdGrade'])){
var_dump($classGrades);
$studentName = $_POST['StdName'];
$studentGrade = $_POST['StdGrade'];
$classGrades['name'][] = $studentName;
$classGrades['grade'][] = $studentGrade;
echo "<br> <br> Your name is: $studentName and your grade is: $studentGrade <br> <br>";
file_put_contents("students.json",json_encode($classGrades));
}
echo "<table><tr><th>Name</th><th>Grade</th></tr>";
for ($i = 0;$i < count($classGrades['name']);$i++){
echo "<tr><td>".$classGrades['name'][$i] . "</td><td> " .$classGrades['grade'][$i] . "</td></tr>";
}
echo "</table>";

how to set array data for the textbox in php

**I have home.php file and superLec.php file. user can enter studentUniversityId and click on the submit button. particular data i want to show studentName textbox and lecturerName textbox. I want to pass data as a array. How to set array data for textbox value.Please any one help me. **.
home.php
<?php
session_start();
include_once 'include/class.supervisor.php';
$supervisor = new Supervisor();
if (isset($_POST['submit'])) {
extract($_POST);
$autofill = $supervisor->check_auto_fill($studentUniversityId);
/* if ($autofill) {
// Registration Success
header("location:homeLecturer.php");
} else {
// Registration Failed
echo 'Wrong username or password';
}*/
}
?>
<form action="" method="post">
<label for="studentID">Student ID</label>
<input type="text" name="studentUniversityId" id="studentID" placeholder="studentID">
<!--input type="submit" id="autoFill" name="autoFill" value="Auto Fill"><br><br>
<input class="btn" type="submit" name="submit" value="Auto Fill"-->
<label for="studentName">Student Name</label>
<input type="text" id="studentName" name="studentName" value = "<?php echo print_r($autofill);?>" placeholder="Student Name"><br><br>
<label for="lecturerName">Supervisor Name</label>
<input type="text" id="lecturerName" name="lecturerName" value = "<?php echo ($lecturerName) ;?>" placeholder="Supervisor Name"><br><br>
<input type="submit" id="submit" name="submit" value="submit">
</form>
**This is my php file. I want pass array values for the home.php file. can any one help me pls. **
superLe.php
public function check_auto_fill($studentUniversityId){
$query = "SELECT supervisor.lecturerName, supervisee.studentName, supervisee.studentUniversityId FROM supervisee, supervisor WHERE supervisee.lecturerId = supervisor.lecturerId AND supervisee.studentUniversityId = '$studentUniversityId' ";
$result = $this->db->query($query) or die($this->db->error);
$supervisor_data = $result->fetch_array(MYSQLI_ASSOC);
$arr = array("lecturerName", "studentName", "studentName");
return $arr;
}
You have to use JQuery function to set value of form elements.
Post studentUniversityId via ajax get data in response and populate the data to form element.
To create a response with array, you need to extract the fetched data from query and put them into the output array.
I suggest you to use a key/value array.
public function check_auto_fill($studentUniversityId){
$query = "SELECT supervisor.lecturerName, supervisee.studentName, supervisee.studentUniversityId FROM supervisee, supervisor WHERE supervisee.lecturerId = supervisor.lecturerId AND supervisee.studentUniversityId = '$studentUniversityId' ";
$result = $this->db->query($query) or die($this->db->error);
$supervisor_data = $result->fetch_array(MYSQLI_ASSOC);
$arr = array(
'lecturerName' => $supervisor_data[0]['lecturerName'], //the "0" index depends of the query structure, but as I can see, this is a right way
'studentName' => $supervisor_data[0]['studentName'],
)
//$arr = array("lecturerName", "studentName", "studentName");
return $arr;
}
After that in your home.php you can simple extract the data from array and put the elements in the right fields as exampled:
<label for="studentName">Student Name</label>
<input type="text" id="studentName" name="studentName" value = "<?php echo $autofill['studentName']; ?>" placeholder="Student Name"><br><br>
<label for="lecturerName">Supervisor Name</label>
<input type="text" id="lecturerName" name="lecturerName" value = "<?php echo $autofill['lecturerName']; ?>" placeholder="Supervisor Name"><br><br>
Hope it help you.
Marco
From what I see and understand (please excuse if I don't), you want to populate the text fields studentName and lecturerName with their respective values. To me, you code looks correct except one thing. You need to drop the line
$arr = array("lecturerName", "studentName", "studentName");
from superLe.php. The line
$supervisor_data = $result->fetch_array(MYSQLI_ASSOC);
already returns an associative array, which you can use in the variable $autofill in file home.php as $autofill['studentName'] or $autofill['lecturerName'].

PHP - Insert elemens into an array

I'm working on a formular, but for the moment I just want to insert into an array my elements (I have books and authors).
I can display my books with author (name + surname) with the foreach, but I can't add more elements.
Here is the code with the form.
<H1>Exercice 2</H1>
<form method="POST">
<label for"code" >Number :</label>
<input id="code" name="code" type="number" />
<label for"title">Title :</label>
<input id="title" name="title" type="text" />
<label for"author" >Author :</label>
<input id="author" name="author" type="text" />
<button type="input" type="submit">Ok</button>
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = array();
$book['code'] = 123;
$book['title'] = "Legendes";
$book['author'] = array("David", "Gemmel");
foreach($book as $value){
$book['key'] = $value;
var_dump($book);
if (is_array($value)) {
foreach($value as $otherValue) {
echo($otherValue);
}
} else {
echo($value);
}
}
I did some searcch, but I don't think it works, it's using the array_push() method with the POST, but I don't know where I can manipulate my form into the array.
If you want some details, I'll be happy to do that =) I'm working on it, if i have some news, you will know =)
Have a nice day =)
1) Assignments are in reverse. Correct way:
$myVar = $myValue
2) You need to set the name attribute in your inputs in order to be sent:
<input id="code" type="number" name="code" />
Then you can access them like:
$_POST['code']
3) To add an element by key in an array, use:
$array['key'] = $value;
Your Exercise 2 have some mistakes :
First, your HTML inputs must have the name attribute to be retrieved by post:
<h1>Exercice 2</h1>
<form method="post">
<label>
<input name="code" type="number" />
</label>
<button type="submit">Ok</button>
</form>
With PHP, you can access to any input value using the name:
$code = $_POST['code'];
Now, I think you want to "add" several books using this HTML form without a storage system. The problem is you can not do this if for every a new request since all the elements you have in your array will be deleted each time you run a new post request. To keep this information you need to use some persistent storage system as a database or others.
Since you seem to want to keep the information for each book together, you need to use a multidimensional array - hence, you'll need to redo the whole thing. Here's a suggestion:
Form:
<h2>Exercice 2</h2>
<form method="post">
<label for"code">Number :</label>
<input id="code" name="code" type="number">
<label for"title">Title :</label>
<input id="title" name="title" type="text">
<label for"author-firstname">Author First Name:</label>
<input id="author-firstname" name="author-firstname" type="text">
<label for "author-lastname">Author Last Name:</label>
<input id="author-lastname" name="author-lastname" type="text">
<input type="submit" name="submit_book" value="Ok">
</form>
Fixed the name-problems, changed the heading (you never, ever use H1 for a form, H1 is strictly used for the site-wide heading/logo/name of site). Also changed the button into a simple input type="submit".
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = []; // changed this to modern PHP version array assignment
$book[0]['code'] = 123;
$book[0]['title'] = "Legendes";
$book[0]['author-firstname'] = "David";
$book[0]['author-lastname'] = "Gemmel"; // no reason to assign a separate array for first and last name, just use two array-keys
for ($c = 0; $c <= count($book); $c++) { //changed this to a for, counting the amount of entries in the $book array
echo 'Title: '.$book[$c]['title'];
echo 'Author: '.$book[$c]['author-firstname'].' '.$book[$c]['author-lastname'];
} // the content should probably be wrapped in a container of some sort, probably a <li> (and then a <ul>-list declared before the for-loop)
Now. None of this has anything to do with putting stuff INTO the array. That would be something like this (there isn't even a point of assigning the $_POST-variables for the code you posted. But, you can do something like this:
if (isset($_POST['submit_book'])) {
$title = $_POST['title'];
$code = $_POST['code'];
$author-firstname = $_POST['author-firstname'];
$author-lastname = $_POST['author-lastname'];
// however, if all you're doing is putting this into the array, no need to assigne the $_POST to variables, you can just do this:
$temp_array = ['code'=>$_POST['code'],'title'=>$_POST['title'],'author-firstname'=>$_POST['author-firstname'],'author-lastname'=>$_POST['author-lastname']];
$book[] = $temp_array;
}
So, that would replace the assigned variables at the beginning of your code.

Loop through 3 arrays at once and save values in the database

I have three inputs type text in an HTML page and a button which if clicked duplicate each text box (Javascript) making them 6.
<input type="text" name="category[]">
<input type="text" name="quantity[]">
<input type="text" name="amount[]">
<button>Add more</button>
Which generate same inputs again:
<input type="text" name="category[]">
<input type="text" name="quantity[]">
<input type="text" name="amount[]">
A piece of code in Cakephp I have been trying:
$data = $this->request->data;
foreach($data['category'] as $index => $value){
$this->ModelName->save($value);
}
Trying to get two rows inserted at once with quantity, category and amount as columns. But it is not inserting and not giving any error.
Is there a way I can achieve this?
Thanks.
I'm not sure how your model works in cakephp, but you should be able to get a complete grouping of data like:
foreach($data['category'] as $index => $value){
$category = $value
$quantity = $data['quantity'][$index];
$amount = $data['amount'][$index];
// use the above 3 variables however you need to to persist the model
//$this->ModelName->save($value);
}
On a side note, you may want to consider reordering your html inputs to be like:
<input type="text" name="item[0][category]">
<input type="text" name="item[0][quantity]">
<input type="text" name="item[0][amount]">
And then maintain the next index, incrementing the numeric index of item for each additional group
This will allow you to iterate like:
foreach($data['item'] as $index => $group){
//$group['category'];
//$group['quantity'];
//$group['amount'];
}

How to submit a single form value multiple times and store (preserve) them in an array each time that I refresh my page?

Attempt 1: This shows what I want to achieve. The same array but different key and value pair.When printed, it list out all the keys and values.
<?php
$rental[]=array('day'=>1,'rate'=>10);
$rental[]=array('day'=>2,'rate'=>20);
$rental[]=array('day'=>3,'rate'=>30);
$rental[]=array('day'=>4,'rate'=>40);
print_r($rental);
?>
Attempt 2: Now, I'm using a single form to submit multiple times.I expect the key and values to be stored inside an array each time the form is submitted. But what happens is, the last value pair overwrites the previous one.Therefore only one pair is shown. So far, I can store them with the help of session. But I just wonder if there's a way to achieve it via php array on the same page?
<?php
$rental[]=array('day'=>$_POST['days'],'rate'=>$_POST['rental']);
print_r($rental);
?>
<form action="#" method="post">
Number of Days: <input type="text" name="days" value=""><br/>
Rental rate: <input type="text" name="rental" value=""><br/>
<input type="submit" name="add_rental_rate" value="Add Rental Rate">
</form>
You can use session to achieve what you want, see this code:
<?php
session_start();
if(isset($_POST['days']) && isset($_POST['rental'])){
$_SESSION['info'][] = array($_POST['days'] => $_POST['rental']);
}
if(isset($_SESSION['info'])) {
for($i = 0; $i < count($_SESSION['info']); $i++) {
foreach($_SESSION['info'][$i] as $days => $rental){
echo '<p>' . $days . '<br>';
echo $rental . '</p>';
}
}
}
?>
<form action="#" method="post">
Number of Days: <input type="text" name="days" value=""><br/>
Rental rate: <input type="text" name="rental" value=""><br/>
<input type="submit" name="add_rental_rate" value="Add Rental Rate">
</form>
You should read some docs about session:
http://php.net/manual/en/intro.session.php

Categories