I'm searching a way to create arrays from a form and transfer it to another page:
This is my actual code :
<?php
$nba = $_GET["nbadultes"]; // recup number of passangers
$adu = array();
for ($i=1;$i<=$nba;$i++)
{
echo '<h3>Passager '.$i.'</h3>
<label>CIVILITÉ</label>
<select class="full-width" name="Civilite">
<option value="Mr" selected >Mr.</option>
<option value="Mrs" >Mrs.</option>
</select>
<label>FIRSTNAME *</label>
<input type="text" name="FIRSTNAME"/>
<label>LASTNAME *</label>
<input type="text" name="LASTNAME"/> ';
$adu[$i][civilite] = $_POST['civilite'];
$adu[$i][FIRSTNAME] = $_POST['FIRSTNAME'];
$adu[$i][LASTNAME] = $_POST['LASTNAME'];
}
$_SESSION['liste_adultes'] =$adu;
?>
And this code in the next page to read the array :
<?php
if (isset($_SESSION['liste_adultes']))
print_r ($liste_adultes);
?>
But I don't know why the array is empty :
Array
(
[1] => Array
(
[Civilite] =>
[FIRSTNAME ] =>
[LASTNAME] =>
)
[2] => Array
(
[Civilite] =>
[FIRSTNAME ] =>
[LASTNAME] =>
)
)
You need to take care of the form inputs you send
As I can see, right now the form is not submitted, so you don't need a session but a form which have set the action to a page that handles the sent data. Something like:
<form method="post" action="my-action-file.php">
<?php
$nba = $_GET["nbadultes"];
for ($i = 1; $i <= $nba; $i++) {
echo '<h3>Passager '.$i.'</h3>
<label>CIVILITÉ</label>
<select class="full-width" name="Civilite[]">
<option value="Mr" selected >Mr.</option>
<option value="Mrs" >Mrs.</option>
</select>
<label>FIRSTNAME *</label>
<input type="text" name="FIRSTNAME[]"/>
<label>LASTNAME *</label>
<input type="text" name="LASTNAME[]"/> ';
}
?>
<input type="submit" value="Submit" />
</form>
In the my-action-file.php file you can get the $_POST variables as:
<?php
foreach ($_POST['Civilite'] as $key => $civilite) {
$firstName = $_POST['FIRSTNAME'][$key];
$lastName = $_POST['LASTNAME'][$key];
// now you have the sent data.. just use it like you need..
}
// of course you can add these data to an array if you like so
In the second page you need to read the session data, then read the specific value you saved in the session into the variable you used:
<?php
if(!isset($_SESSION)){ session_start();}
if(isset($_SESSION['liste_adultes'])){
$liste_adultes = $_SESSION['liste_adultes'];
print_r($liste_adultes);
}
?>
Also, in the first page, make sure you post data and read it with $_POST; or via query string with $_GET
Related
I have made the following form in HTML:
<form method="post" action="survey.php">
<div>
<label class="prompt">Favorite CS courses:</label>
<label>
<input type="checkbox" name="courses[]" value="course-web">Web Development
</label>
<label>
<input type="checkbox" name="courses[]" value="course-net">Networking
</label>
<label>
<input type="checkbox" name="courses[]" value="course-gui">GUI
</label>
<label>
<input type="checkbox" name="courses[]" value="course-oop">OOP
</label>
</div>
<div>
<input type="submit" value="Submit Survey">
</div>
</form>
When the user submits the form, it submits to a PHP file that I have. In the file, I have the following variable assignment to receive the courses[] from HTML:
$courses = $_POST["courses"];
In my PHP code, I have the following foreach loop so that I can print out the values from the array:
// output the user's favorite courses
echo "<p>Favorite Courses:</p> <ul>";
foreach ($courses as $course)
{
echo "<li><strong>$course</strong></li>";
}
echo "</ul>";
The problem is that when I ouput the courses, it comes out like this:
Favorite Courses:
course-web
course-net
course-gui
course-oop
I would like to change my code so that it outputs it like this:
Favorite Courses:
Web Development
Networking
GUI
OOP
How should I go about doing this without changing any of the HTML code.
The best solution that I have come up with for this problem is the following code, but I feel like it could be improved a lot:
// output the user's favorite courses
echo "<p>Favorite Courses:</p> <ul>";
foreach ($courses as $course)
{
if ($course == 'course-web')
{
echo "<li><strong>Web Development</strong></li>";
}
if ($course == 'course-net')
{
echo "<li><strong>Networking</strong></li>";
}
if ($course == 'course-gui')
{
echo "<li><strong>GUI</strong></li>";
}
if ($course == 'course-oop')
{
echo "<li><strong>OOP</strong></li>";
}
}
echo "</ul>";
Create an array that maps values submitted by the form to human-readable names:
$names = [
'course-web' => 'Web Development',
'course-net' => 'Networking',
'course-gui' => 'GUI',
'course-oop' => 'OOP',
];
Loop through the array of values received and look up the human-readable name in the array:
foreach ($courses as $course)
if ( strlen( $name = $names[ $course ] ) ) { // Yes, assign
echo "<li><strong>$name</strong></li>";
}
}
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>";
I am trying to find out online how to make a form loop based on a dropdown value. So for example, If the dropdown is selected on 2, it will loop a preset form twice, if the option was 3 it would display the form 3 times. This would be helpful because I am trying to get those forms into an array and then use the array to send to phpmyadmin etc.
Another question is how would I be able to get the value of each form being displayed, unless I can have the code differentiate between the forms, it might just see the values as one instead of two separate if that makes sense.
<html>
<?php
session_start();
?>
<?php include 'AdminHeader.php' ?>
<?php include '../Includes/dbh.inc.php' ?>
<body bgcolor="grey">
<div class="main">
<form method="POST">
<select name="RaceNum">
<option> Number of Horses </option>
<option> 1 </option>
<option> 2 </option>
</select><br />
Horse Number: <input type="text" name="HorseNumber"><br/>
Horse Name: <input type="text" name="HorseName">
<button type="Submit" name="submit"> Submit </button>
</form>
<?php
if(isset($_POST['submit'])) {
$RaceNum = $_POST['RaceNum'];
$HorseNumber = $_POST['HorseNumber'];
$HorseName = $_POST ['HorseName'];
while($RaceNum < 2){
$stack = array(
1 => array( 'Horse Number' => $HorseNumber, 'Horse Name' => $HorseName )
);
echo "<pre>";
print_r($stack);
echo "</pre>";
}
}
?>
**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 have read several tutorials to try and get my head around this problem. I have my code working fine with the text input box, but I'm trying to pass the radio box to my function as well and use it to get my array value.
I will implement things like form validation and sanitisation later, but now I just want to be able to output the array result within my function, depending on what radio button was selected. This is the code I have tried:
index.php
<?php
if (isset($_POST['submit'])) {
$data = $_POST['name']; // the data from text input.
$colour = $_POST['colour']; // data from colour radio.
}
?>
...
<form action="/app.php" method="post">
<input type="text" name="name">
<input name="colour" type="radio" value="1">Red
<input name="colour" type="radio" value="2">Blue
<input name="colour" type="radio" value="3">Green
<input type="submit" name="submit" value="Submit">
</form>
<img src="pngfile.php?data=<?php print urlencode($data);?>">
pngfile.php
<?php
require_once 'functions.php';
$textdata = urldecode($_GET['data']);
$colourdata = urldecode($_GET['colour']);
process($textdata,$colourdata);
exit;
?>
functions.php
<?php
/* Generate Image */
function process($textdata, $colourdata)
{
$colour_array = [
"1" => "#9E2A2B",
"2" => "#3E5C76",
"3" => "#335C67",
];
...
I am stuck with the piece of the code that will take the radio button value (1/2/3) and then look up the equivalent array value and output the colour, i.e: if radio button with value 1 is selected, then we output 1#9E2A2B.
<form action="/app.php" method="post">
form method POST not GET
$_GET['colour'] edit to $_POST['colour']
in function
function process($textdata, $colourdata)
{
$colour_array = [
"1" => "#9E2A2B",
"2" => "#3E5C76",
"3" => "#335C67",
];
$color = isset($colour_array[$colourdata]) ? $colour_array[$colourdata] : false;
...