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>";
Related
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.
I'd like to post a form with inputs and files and retrieve in the destination page in the same order i've got in the form, for example:
<form id="form" method="post" action="">
Description file: <input type="text" name="input-1" value="description 1">
<br>
File: <input type="file" name="input-2">
<br>
<br>
Others data: <input type="text" name="input-3" value="some others unique data">
<br>
Description file: <input type="text" name="input-4" value="description 2">
<br>
File: <input type="file" name="input-5">
<br>
Description file: <input type="text" name="input-6" value="description 3">
<br>
File: <input type="file" name="input-7">
<br>
</form>
<?php
$post = $_POST;
$files = $_FILES;
foreach ( $post as $i => $value ) {
echo "Variables passed: " . $value . "<br>";
}
foreach ( $files as $i => $value ) {
echo "File: " . $value['name'] . "<br>";
}
?>
I'd like an output like:
Variables passed: description 1
File: file1.jpg
Variables passed: some others unique data
Variables passed: description 2
File: file2.jpg
Variables passed: description 3
File: file3.jpg
but i get this, cause i've 2 different foreach:
Variables passed: description 1
Variables passed: some others unique data
Variables passed: description 2
Variables passed: description 3
File: file1.jpg
File: file2.jpg
File: file3.jpg
This is only a simple example. I've a dynamic form where i can add inputs fields in differents ordering with a button.
Is there a way to mantain the same order to destination page?
UPDATE: i've edited my original post: It's not a rule there's always a File input after an input field text.
UPDATE 2: name like input-1, input-2, input-3, input-4, ... are automatically retrieved from mysql db when i click add button to insert a new input.. so they can be in different order like: input-1, input-3, input-2, input-4, ...
Assuming that files will always be accompanied by a description, and descriptions will always be accompanied by a file (you'll need to validate against this). Something like this should point you in the right direction:
<form id="form" method="post" action="">
Description file: <input type="text" name="input-1" value="description 1">
<br>
File: <input type="file" name="file-2">
<br>
Description file: <input type="text" name="input-3" value="description 2">
<br>
File: <input type="file" name="file-4">
<br>
Description file: <input type="text" name="input-5" value="description 3">
<br>
File: <input type="file" name="file-6">
<br>
</form>
<?php
$post = $_POST;
$files = $_FILES;
foreach ( $post as $i => $value ) {
echo "Description: " . $value . "<br>";
echo "File: " . $files[$i]['name'] . "<br>";
}
?>
If you know in advance that the fields will have those names in that format, then you could do something like this:
$len = sizeof($post);
for ($i = 0; $i<len;$i++)
{
$item = $i + 1;
echo "Description: ".$item.": ".$post["input-".$item]."<br>";
echo "File: ".$item.": ". $files["file-".$item]."<br>";
}
Of course if your $_POST also contains other variables, you may need to do something like use a regular expression to filter just those names which match your pattern, and only use those matches in your loop.
And as others have mentioned in the comments, you should always keep in mind the possibility of unexpected inputs.
OK I've finally found a solution.
Before onsubmit, i'll use:
$("body").find(":input[name^='input-']").each(function (index, value) {
var value = $(this).attr("name");
$(form).append('<input type="hidden" name="varsOrder[]" value="' + value + '">');
});
form.submit();
Then in index.php:
// RETRIEVE ONLY $_POST starting with input-
foreach($_POST as $key => $value) {
if (strpos($key, 'input-') === 0) {
$idVars = ltrim($key, "input-");
$vars[$idVars] = $value;
}
}
// RETRIEVE ONLY $_FILES starting with input-
foreach($_FILES as $input => $array) {
if (strpos($input, 'input-') === 0) {
$idVars= ltrim($input, "input-");
// PROCESS FILE
...
$vars[$idVars] = $array['name'];
}
}
// FINAL REORDER
$orderedVars = $vars;
$order = isset($_POST['vars']) ? $_POST['vars'] : array();
if ( count($order ) ) {
$orderedVars = array();
foreach ( $order as $index => $nameVar) {
$idVar = ltrim($nameVar, "input-");
if ( array_key_exists($idVar, $vars) ) {
$orderedVars[] = $vars[$idVar];
}
}
}
// $orderedVars AT THIS POINT IS AN ARRAY OF ORDERED INPUTS LIKE ORIGINAL FORM
**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'].
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.
DEMO.PHP
<form action = "test.php" method="post">
<input type="checkbox" name="vehicle[]" value="'Peter'=>'35'">I have a bike<br>
<input type="checkbox" name="vehicle[]" value="'Ben'=>'37'">I have a car <br>
<input type="submit" value="Submit">
</form>
test.php
<?php
if(isset ($_POST["vehicle"]))
{
$v = $_POST["vehicle"];
foreach($v as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
}
?>
My $x didnt get Peter or Ben?
How can I get the key and value separately?
If you name your fields ending in [], then PHP will construct a regular array from them.
Using => in the value will have no special meaning.
If you want to specify the key names that PHP will parse the form data into, then you do so in the name:
name="vehicle[Peter]" value="35"