Why is my included file executed again when isset(POST['submit'])? - php

My included file (include.php) is this:
<?php
$myarray=(a,b,c);
shuffle($myarray);
?>
My main php file is this:
include('include.php');
if isset($_POST['submit_button']){
echo "Button was clicked";
echo $myarray;
}
else {
echo "Not clicked.";
echo $myarray;
}
?>
<form method='POST'><input type='submit' name='submit_button'></form>
Why are the elements of $myarray displayed in a different order after I clicked the button? Isn't it shuffled only once?
How can I prevent the shuffle from being executed more than one time? (so that I can display the elements of myarray in the same order, before and after the button was clicked)

Your PHP files are interpreted upon every request. As you have it now, there is no memory in your system, so there's no way for your files to "remember" that the array has already been shuffled. Furthermore, if you shuffle the array once, and then load the page a second time, and managed not to shuffle it, the array would be (a,b,c), as the variable is initialized to (a,b,c) and never shuffled.
To do what you want, if I understand it correctly, you could use sessions.
$myarray=(a,b,c);
if (!isset($_SESSION['shuffled'])) {
shuffle($myarray);
$_SESSION['shuffled'] = $myarray;
} else {
$myarray = $_SESSION['shuffled'];
}

This is happening because each time you load the page, the file is being included which also shuffles the array again.
Try using serialize() and then POST the array in the order you want. Retrieve it using unserialize()
http://www.php.net/manual/en/function.serialize.php

Related

How to update an array in another PHP file?

I have index.php file and it contains:
1.class eachObject
class eachObject
{
function outPut()
{
echo '<td> </td>';
}
}
2.class wall
class wall extends eachObject
{
function outPut()
{
echo '<td class="wall"> </td>';
}
}
3.class blank
class blank extends eachObject
{
function outPut()
{
echo '<td class="blank"> </td>';
}
}
I got instances from them:
$wall = new wall();
$blank = new blank();
and I have an array called room including wall and blank:
$room = array();
$room[0] = array($wall, $wall, $blank, $wall, $blank);
and then I will use it in a table to show walls and blanked areas:
<html>
<body>
<?php
echo '<table>';
foreach ($room as $row) {
echo '<tr>';
foreach ($row as $tool) {
$tool->outPut();
}
echo '</tr>';
}
echo '</table>';
?>
</body>
</html>
The question is: how can I change this array in another php file called test.php to have:
$room[0] = array($wall, $wall, $wall, $wall, $blank);
As you can see, the third value changed from $blank to $wall.
and then when I refresh the div which contains the table, I will have a wall instead of blank area.
Since test.php is included/required to index.php, $rooms can be modified there using
$rooms[0][3] = $wall;
but note that this is only possible if both $rooms and $wall are reachable. If you declare them as globals before you include/require test.php and after you include/require index.php you do some changes for $room[0], then it should work and you should have a new value. From your description it seems that you either included/required test.php before $rooms and/or $wall is defined, or the variables are out of context, for instance, inside a function. You will need to make sure that the variables are reachable in the other file and when the other file starts to use them, they are already declared. However, you might want to rethink the way your code is structured and use some ideas like MVC. If this answer is not enough for you to solve your problem, then you will need to add more details about your code.
Create a functional construct (class with methods, function, ...) that first deletes your old test.php file, then creates a new one, adding line by line the content you wanted to add. (See the Php filesystem functions for such an application)
That is a way that works, but it is not a way I would recommend. (But I do not know your project, I might not see the whole image) Better would be a way using a serialised array. So you serialise your new array, save that string to your file and each time you want to use your array, just deserialise the string in your file. And last method: use a database, if possible.
you can change the value per
$room[0][3] = $wall;

send array via session in php

i have this array
$banners[0] ='a';
$banners[1] ='s';
$banners[2] ='d';
$banners[3] ='f';
I shuffle this array with
shuffle($banners);
and than I have new random list, which I can show with
echo $banners[0];
echo $banners[1];
echo $banners[2];
echo $banners[3];
and this new random list I want to put in session and send to another page on my website
This doesn't work
session_start();
$_SESSION['sesion'] = $banners;
another page:
$banners[0] ='a';
$banners[1] ='s';
$banners[2] ='d';
$banners[3] ='f';
$banners = $_SESSION['sesion'];
echo $banners[0];
echo $banners[1];
echo $banners[2];
echo $banners[3];
how I can send new shuffle banners to another page with session? thans
You need session_start() at the top of every page.
You missed the statement to start the session in the 2nd page.
So you need session_start(); to be executed before you can access a SESSION variable through $_SESSION[]

How to pass variable in Ajax, PHP

I use PHP for almost one year, but I encounter a problem that confuse me for few days. As we know that we can use Ajax to pass variable to PHP then get response back for display. But how can I get the variable from one block of code to anther? Well Let me describe my problem in the code. Because my code has a very large size, so I just put a simplify version here.
<?php
$array = [1,2,3,4,5];
//first Ajax call
if(isset($_POST['id'])){
$id = $_POST['id'];
$value= $_POST['value'];
$array[$id] = value; //The first call is mainly to update the value of $array
echo $value;
exit();
}
//Second Ajax call
if(isset($_POST['name'])){
print_r($array); //I want to use $array here, but I got the original
..... //one.So what should I do to get the updated $array
//from last Ajax call?
}
If anyone could tell me how to solve it or maybe there is another way to get it, I will be very appreciate.
Your AJAX calls to the page each initialise a new set of variables. You can't access $arrray from consecutive calls, but you could access a session variable.
Add session_start(); at the top of the page, then
<?php
//first Ajax call
if(isset($_POST['id'])){
$_SESSION['id'] = $_POST['id'];
$_SESSION['value'] = $_POST['value']; //The first call is mainly to update the value of $array
echo $_SESSION['value'];
exit();
}
//Second Ajax call
if(isset($_POST['name'])){
echo $_SESSION['id'],"<br>";
echo $_SESSION['value'],"<br>";
}
Note: this snippet is making assumptions about the order of execution that might not be justified. For production code you should test the presence of $_POST and $_SESSION variables before you use them.

Auto Generate JS variables if data in array exists PHP/MySQL

I have a map on my site that has plots placed on it using data from my table. The plots are placed with javascript as so...
addPostCode('<?php echo $array[$UID][0]; ?>');
addPostCode('<?php echo $array[$UID][1]; ?>');
addPostCode('<?php echo $array[$UID][2]; ?>');
Somehow I need to see if the variable exists in my table, and then if so, generate an additional line and increment my array number, so based on the above 3 records, the next line would be...
addPostCode('<?php echo $array[$UID][4]; ?>');
Can I ask if this is possible?
You just need to loop through all of the members of the $array[$UID] variable.
<?php
foreach($array[$UID] as $thing) {
$encodedThing = json_encode($thing);
echo "addPostCode($encodedThing);\n"
}
?>
I used json_encode() because it does whatever escaping is necessary to make your data JavaScript-compatible.
If I understand you well, this is what you would do:
addPostCode('<?php $i=0; while (isset( $array[$UID][$i])) { echo $array[$UID][$i]; $i++ ; } ?>');
That would replace all your addPostCode() calls also.

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