My array values keep dissapearing and refreshing in php? - php

I want to be able to add new values to the array called playlist using functions (is mandatory). But everytime I input another value it replaces the old one instead of just adding on the end of the array. What is wrong?
<?php
$playlist = array("Be more.mp3", "Drift Away.mp3", "Panda Sneeze.mp3");
function add_songs_playlist() {
global $playlist;
?>
<form method = "post">
<input type = "text" name = "name1"/>
<input type = "submit" name = "submit1"/>
</form>
<?php
if (isset($_POST['submit1'])) {
$newsong = $_POST['name1'];
array_push($playlist, $newsong);
}
}
add_songs_playlist();
foreach ($playlist as $value) {
echo $value."<br>";
}

PHP values aren't saved between requests. Every time this page loads, $playlist starts out with those same three values you assign.
If you want to keep data around longer, you'll need to save it somewhere—a cookie, a file, the session, a database, etc.
Alternatively, you could store the values in the HTML itself, by printing an <input type="hidden"> for each song in the playlist. Then when the user enters a new song, you have the new song plus the full list of all the old ones.

Just write the playlist to a file
<?php
if (isset($_POST['submit1'])) {
$song = "\n".$_POST['name1'];
$file = fopen("songs.txt", 'a');
fwrite($file, $song);
fclose($file);
}
$file = file("songs.txt");
foreach ($file as $song) {
echo $song . "</br>";
}
?>
<form method = "post">
<input type = "text" name = "name1"/>
<input type = "submit" name = "submit1"/>
</form>

There is a general mistake you make:
you have to understand that each time you transmit a value the way you do, you php script is started again. It restarts without anything left from the last time.
To be able to take over values the way you want to you have to store those values in a persistant manner after having pushed them to the array. During the next run you first have to read the existing values from that persistant storage, fill the array and only then you can add another value on top of that array. This is a general principle, the basic way this kind of framework works.
Typically a database is used as persistant storage, but also files might be interresting, depending on how many request and how much data you plan to process.

Here is an small mod of your code. I removed the function and stored your array within the form itself.
This one will work without storing any information on the server, bet I don't think it wil be very usable. You should store your content like suggested by #Anonymous in previous reply.
Working code:
<?php
// First check if I get a POST request with list of songs
if (isset($_POST['playlist'])) {
$playlist = $_POST['playlist'];
} else { // Else set my default list
$playlist = array("Be more.mp3", "Drift Away.mp3", "Panda Sneeze.mp3");
}
// You need to get the added son BEFORE you generate the FORM,
// so it can be a part of the form
if (isset($_POST['name1'])) {
$playlist[] = $_POST['name1'];
}
?>
<form method = "post">
<?php
// This loop stores your songs as hidden values within the form,
// so you will get them with your next post
foreach($playlist as $song) {
?>
<input type = "hidden" name = "playlist[]" value = "<?php echo $song?>">
<?php
}
?>
<input type = "text" name = "name1"/>
<input type = "submit" name = "submit1"/>
</form>
<?php
foreach ($playlist as $value) {
echo $value."<br>";
}

An example specific to your repost code would be:
if (isset($_POST['submit1'])) {
$newsong = $_POST['name1'];
$playlist[] = $newsong;
}
Also an error may be the fact your form is within a function... why not just do this
<?php
$playlist = array("Be more.mp3", "Drift Away.mp3", "Panda Sneeze.mp3");
?>
<form method = "post">
<input type = "text" name = "name1"/>
<input type = "submit" name = "submit1"/>
</form>
<?php
if (isset($_POST['submit1'])) {
$newsong = $_POST['name1'];
$playlist[] = $newsong;
}
foreach ($playlist as $value) {
echo $value."<br>";
}
?>
I am not sure if you care if the page refreshes. But if you are fine with a page refresh this should work. If you do not want a refresh you can either save your variables in javascript and do your work in that and use the form button onClick as a function call. Or if you want to work your variables in PHP in-order to reset your php variable without refreshing you will need to make an AJAX call to call back JSON to update your PHP variable.

Related

Get the dynamically generated name from the form into the $_POST

I'm currently working on a personal content management system project, but I've run into a problem.
<ul>
<?php
if(!$result) { //Check for result
die("You have no pages &#9785 Why not create one?");
} else {
while ($pages = mysqli_fetch_assoc($result)) { //Loop through results
?>
<li class="triple"><span><?php echo $pages["title"]?></span><span><?php echo $pages["visible"] ?><span /><form action = "editPage.php" method="post"><input type="submit" value="Edit Page" name="<?php $pages["title"];?>" /></form></li> //Create li elements for each result that gets created
<?php
};
};
?>
</ul>
Basically I'm using a query to results from a MySQL table and make a list of pages, the problem I've run into is that on the end form what I want to happen is I want a session variable to be stored saying which page is going to be edited, but I can't use $_POST in the form at the end to get the name because obviously the name is automatically generated from the table. Each person who uses it would have a different name for a page so I can't just get one name e.g. $_POST['homepage'].
If anyone can offer any advice on how to solve my problem or even how to come up with a better solution to store which page will be edited as it goes onto another page (editPage.php) that would be great.
Use $_SESSION[] to store the data for your $page arrays and access it again on editPage.php. You will need to make sure you call start_session(); on both pages though for it to work as expected. Since you're creating multiple forms and don't know which one will be submitted at the time PHP is running you would need to store all the pages in your $_SESSION and then iterate through them to check for the one which was selected in editPage.php:
$_SESSION['pages'] = array();
while ($page = mysqli_fetch_assoc($result)) {
$_SESSION['pages'][] = $page;
echo "<li class=\"triple\">
<span>".$page["title"]."</span>
<span>".$page["visible"]."</span>
<form action=\"editPage.php\" method=\"post\">
<input type=\"hidden\" name=\"pageID\" value=\"".$page['id']."\">
<input type=\"submit\" value=\"Edit Page\">
</form>
</li>";
}
Then in editPage.php
foreach($_SESSION['pages'] as $page){
if($page['id'] == $_POST['pageID']){ $editpage = $page; break; }
}
// do stuff with $editpage data
Another option would be to use serialize($page) and send the array with the form data in a hidden input element.
<input type='hidden' name='data' value='<?php echo serialize($page); ?>'>
Then you can use $editpage = unserialize($_POST['data']); to turn it back into an array in editPage.php.

Passing values(array) from a checkbox in a php page to another php page using jinput

I am trying to retrieve the value of checkboxes when selected in a form. I have used the following method to store all the check boxes in an array; using [] after the input name:
<input type="checkbox" class="form-control" name="documents[]" value="<?php echo $this->user->construction; ?>" />Construction of building<br/>
And then I store the selected values right after, on submit:
if(isset($_POST['submit'])){//to run PHP script on submit
if(!empty($_POST['documents'])){
// Loop to store and display values of individual checked checkbox.
foreach($_POST['documents'] as $selected){
echo $selected."</br>";
}
}
}
On the other php page, I try to retrieve the value of the selected checkboxes in the variable call "documents":
$app = JFactory::getApplication();
$documents = $app->input->getVar('documents',array());
But after retrieving the data, the only value returned is = Array.
Any help will be appreciated.
I was finally able to get this done on my own:
$docs = $_POST['documents'];
foreach ($docs as $documents)
{
$msg .= "$documents\n" ;
}
Then I used the variable, $msg to hold the values of the checkbox in the array.
To retrieve a JForm post data using Jinput, you can use
$jinput = JFactory::getApplication()->input;
$formData = new JRegistry($jinput->get('jform', '', 'array'));
$documents= $formData->get('documents','');

how to add input to a variable?

I have this form
<form action="process.php" method="post">
Team Name: <input type="text" name="teamname" />
<input type="submit" />
</form>
and this is my php code
$teamname = $_POST['teamname'];
$namelist = "Lakers";
so let's say two people have submitted their team names as Spurs and Rangers
so how do I make the namelist like this and grow as more people submit their team names..
$namelist = "Lakers, Spurs, Rangers";
I have done it in array_push with arrays, but technically i can't call them.
you need to save the names to file/database.
variable save in the memory of the machine and deleted after the scripts done.
$names = array(); // empty array
$names[] = $_POST['teamname']; // add the $_POST['teamname'] to the array
var_dump($names); // prints the names array.
// now the script done, and all the data in the variables will flush from the memory.
You can use array to solve this issue
<?php
$teamname = $_POST['teamname'];
$namelist = $array("Lakers");
array_push($namelist,$teamname);
print_r($namelist);
?>
using database is a simple solution.
but if you still not like to use database in this situation, you can save the variables as a session or cookie variable. it will remain after page refresh.

How to call upon a PHP function on button click?

I am trying to setup a website that converts a Steam user ID into an auth ID. It will ask for the visitor to input their regular Steam ID and then hit a button to convert it to auth ID. Steam provides us with the function for ID conversion from one type to the other.
Steam function for converting IDs:
function convert_steamid_to_accountid($steamid)
{
$toks = explode(":", $steamid);
$odd = (int)$toks[1];
$halfAID = (int)$toks[2];
$authid = ($halfAID*2) + $odd;
echo $authid;
}
Below is my attempt at setting up a basic HTML page that gets user input and then uses the function to convert that input to something else.
<INPUT TYPE = "Text" VALUE ="ENTER STEAM:ID" NAME = "idform">
<?PHP
$_POST['idform'];
$steamid = $_POST['idform'];
?>
Also, this is what the default Steam user ID looks like:
STEAM_0:1:36716545
Thank you for all the help!
If you can make it into two seperate files, then do so.
foo.html
<form method="POST" action="foo.php">
<input type="text" value="ENTER STEAM:ID" name="idform" />
<input type="submit" />
</form>
foo.php
<?php
function convert_steamid_to_accountid($steamid)
{
$toks = explode(":", $steamid);
$odd = (int)$toks[1];
$halfAID = (int)$toks[2];
$authid = ($halfAID*2) + $odd;
echo $authid;
}
$id = $_POST['idform'];
convert_steamid_to_accountid($id)
?>
if you don't have an option of making two seperate files, you can add the php code to 'foo.html' file and make the form to submit to the same file. However if you do this, check if the file is getting requested the first time, or it is requested because the form is submitted, BEFORE you call convert_steamid_to_accountid() function.
You can do this by:
if ($_SERVER['REQUEST_METHOD']=='POST'){
// your php code here that should be executed when the form is submitted.
}

PHP quiz send data to next page

ok, i'm trying to do a quiz...all good by now. but when i'm trying to send the collected data(radio buttons values) through pages i can't get the logic flow. I have the main idea but i can;t put it into practice.
i want to collect all radio values
create an array containing this values
serialize the array
put the serialized array into a hidden input
the problem is that i want to send data on the same page via $_SERVER['PHP_SELF'] and i don;t know when in time to do those things.(cause on "first" page of the quiz i have nothing to receive, then on the "next" page i receive the S_POST['radio_names'] and just after the second page i can get that hidden input). i hope i made myself understood (it's hard even for me to understand what my question is :D )
You could try to use the $_SESSION object instead... For each page of your quiz, store up the results in the $_SESSION array. On the summary page, use this to show your results.
To accomplish this, on the beginning of each page, you could put something like:
<?
session_start();
foreach ($_POST as $name => $resp) {
$_SESSION['responses'][name] = $resp;
}
?>
Then, on the last page, you can loop through all results:
<?
session_start();
foreach ($_SESSION['responses'] as $name => $resp) {
// validate response ($resp) for input ($name)
}
?>
Name your form fields like this:
<input type="radio" name="quiz[page1][question1]" value="something"/>
...
<input type="hidden" name="quizdata" value="<?PHP serialize($quizdata); ?>"/>
Then when you process:
<?PHP
//if hidden field was passed, grab it.
if (! empty($_POST['quizdata'])){
$quizdata = unserialize($_POST['quizdata']);
}
// if $quizdata isn't an array, initialize it.
if (! is_array($quizdata)){
$quizdata = array();
}
// if there's new question data in post, merge it into quizdata
if (! empty($_POST)){
$quizdata = array_merge($quizdata,$_POST['quiz']);
}
//then output your html fields (as seen above)
As another approach, you could add a field to each "page" and track where you are. Then, in the handler at the top of the page, you would know what input is valid:
<?
if (isset($_POST['page'])) {
$last_page = $_POST['page'];
$current_page = $last_page + 1;
process_page_data($last_page);
} else {
$current_page = 1;
}
?>
... later on the page ...
<? display_page_data($current_page); ?>
<input type="hidden" name="page" value="<?= $current_page ?>" />
In this example, process_page_data($page) would handle reading all the input data necessary for the given page number and display_page_data($page) would show the user the valid questions for the given page number.
You could expand this further and create classes to represent pages, but this might give you an idea of where to start. Using this approach allows you to keep all the data handling in the same PHP script, and makes the data available to other functions in the same script.
You want to use a flow such as
if (isset $_POST){
//do the data processing and such
}
else {
/show entry form
}
That's the most straight forward way I know of to stay on the same page and accept for data.

Categories