How to traverse an array back n forth - php

I have an array something like this
$steps = explode("[;;]",$str);
So the $steps holds value that I have to use to show a step/step procedure in PHP .
The array looks like this
$steps = array('corredores' , 'something' , 'something'...and so one );
I am trying to display forms according to the value saved in the array . I am able to go forward using some validation but I have trouble in moving to the previous name in the array ,
for the first step I am doing something like this
$steps = explode("[;;]",$_POST['str']);
$x = explode("=",$steps[0]);
$pais1 = $_POST['pais'];
$cnt=0;
switch($steps[0]){
case 'categorias' :
include 'obj/categorias.php';
//$step='categorias';
break;
case 'corredores':
include 'obj/corredores.php';
//$step='corredores';
break;
case 'monedas':
include 'obj/monedas.php';
//$step='monedas';
break;
case 'location':
include 'obj/location.php';
//$step='location';
break;
default:
break;
}
//Here I am trying to match the next value from the array that I will save in this post value on every step
if(isset($_POST['next1']) &&$_POST['method'] != "fase1")
{
$cnt =$_POST['cnt'];
$cnt++;
$array_var = unserialize(base64_decode($_POST["next1"]));
$steps = $array_var;
$pais1 = $_POST['pais'];
$x = explode("=",$array_var[$cnt]);
include 'obj/'.trim($x[0]).'.php';
//$step='categorias';
}
So when I click on the next button of each file it goes to the next file in the array , But Now I need to add similar functionality to the previous button so that it goes back
The HTML content of every files has following structure
<form method="post" action="./index.php" name="form_name">
<table><tr><th>Some Name</td></tr>
<tr><td><input type="submit" value="previous"></td><td><input type="submit" value="next"></td></tr></table>
<input type="hidden" name="next1" value="<?php print base64_encode(serialize($steps)) ?>">
<input type="hidden" name="pais" value="<?php echo $pais1?>"/>
<input type="hidden" id="cnt" name="cnt" value="<?php echo $cnt ?>" />
</form>
Can any one give me some suggestion
Thanks in Advance

If I am not reading your code wrong, you already have an array of all the objects stored in next1 and cnt as your currently counter. Essentially, what you need to do is to detect whether the user has pressed the Next or Previous button
<input type="sumbit" name="next" value="Next">
<input type="submit" name="previous" value="Previous">
A form can have more than 1 submit button. Just be sure to name them differently. Then when you process your form:
if (isset($_POST['next'])) {
// go on to the next object
$cnt = $_POST['cnt'] + 1;
} else if (isset($_POST['previous']) {
$cnt = $_POST['cnt'] - 1;
}
// retrieve object from array and include its file
It is important that you don't increment your cnt like above -- and only increment or decrement it before you press the buttons.
In short, change the value of cnt depending if the user presses Next or Previous.

You can use array_search http://php.net/manual/en/function.array-search.php for identifying acual step and then Add +1 for next step or remove -1 for the previous step

Related

add character to my field in form periodic in a loop

i need a php code that user click on send button in my form automatically add a different character like a - b - c -d to field input.
for example this is my form html code.
<form action="action.php" method="post">
<input type="text" id="phone" name="phone">
<input type="submit" value="send">
</form>
and in action.php like this
echo $_POST['phone'];
user enter 002255 in phone number field and click send button
print 002255 now .
but i want when user click send button for first time , print a002255
and when click send button for second time , print b002255
and next c002255 and next d002255
then make a loop and when click for fifth time , print a002255 again.
What will happened after reaching letter Z? In example below it will reset. I think you need to create an array and index to it. So when user click button index goes +1. Index will be on session because it has to store number. Am beginner too and trying to figure it out. Example:
session_start();
$alphabet = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
if(isset($_POST["submit"])) {
if($_SESSION["Number"] == 0) {
print_r($alphabet[0] . "002255");
$_SESSION["Number"] += 1;
} else {
print_r($alphabet[$_SESSION["Number"]] . "002255");
$_SESSION["Number"] += 1;
if($_SESSION["Number"] > 26) {
$_SESSION["Number"] = 0;
}
}
}

PHP random generated number to show matching name and id corresponding to the random number

how to make something like a random lottery. Very simple, in the fact that it shouldn't be long code.
I just want a form that i user can click a radio button which equals 1 and enter their name. When they submit $min = 1(and stays at 1), $max = $max + 1.
Lets say 10 people select the radio button and hit the first submit button. $min = 1 meaning the lowest random number is 1. Then their name is put into an array along with a matching id corresponding to the number in the variable $max(if 5 people submitted, the $max would be 5, and their id would also be 5 as they submitted fifth.
So if 10 people submit , and then click another submit button below a random generated number will be made with a minimum of $min which is 1 and a maximum of $max (the last person to submit radio button).
if the random generated number was 7, then display the 7th person that submitted the radio button(because their id would match with the random number).
I have been learning php for 2 weeks so im not very good now, but my code goes like this...
<form action="POST" name="form">
<input type="text" name="name">
<input type="radio" name="1" value="1">
<input type="submit" name="submit" value="submit">
</form>
<?php
$min = "";
$max = "";
$person = array();
for($_SERVER["REQUEST_METHOD"] == "POST"){
$max = $max + 1;
$person[$max] = $_POST["name"] . ;
$min = 1;
}
?>
<form action="POST" name="random">
<input type="submit" value="submit">
</form>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST" && $_POST["name"] == "random"){
$rand=------rand($min,$max);
if(//TODO) {
$person[$]
}
}
?>
can someone explain how to make this work please?
Assuming you store everything to a MySQL database a possible solution to retrieve a lottery winner would be:
$DB_winner = mysql_query("select name from participants_table_name");
while($win = mysql_fetch_array($DB_winner){
$winners[] = $win['name'];
}
// and the winner is $the_winer:
$the_winner = $winners[rand(0, sizeof($winners)-1)];
I was going to post a comment but it's busy with trains at the moment so...
You will need to learn and understanding the following for your task
Save the data using a file (json or csv up to you), or mysql if you want to further the project. See tutorials for any of this
Learn how $_POST, isset, for, foreach etc works and what they're used for
My advice is to ignore the above and start with absolute basics. Go through w3schools maybe. You're trying to build a palace when you're struggling with lego

Using the value of a hidden field within a PHP recordset.

I have a form :
<form method="POST">
<input name="imagekey" type="hidden" value="<?php echo $row_images['key']; ?>">
</form>
This returns an integer (the unique key for a recordset 'images'). I'm trying to create a second recordset that includes every value of 'images' with a greater key than the one specified in the hidden value. ie if the hidden value is 5, then the second recordset will include everything with a key 6 and above.
I'm using Dreamweaver to create this, and the recordset code for this is:
SELECT *
FROM images
WHERE `key` > colname
ORDER BY `key` ASC
with colname being:
$colname_images2 = "-1";
if (isset($_POST['imagekey'])) {
$colname_images2 = $_POST['imagekey'];
At the moment, I'm still getting the whole recordset including the hiddenvalue in my second recordset. Am I missing something obvious?
thanks
I think you can minus directly you POST value
if (isset($_POST['imagekey']))
{
$colname_images2 = $_POST['imagekey'] - 1;
}
The way you did you were setting for variable $colname_images2 = "-1" and then you were overwriting it with $_POST['imagekey']
in other hands you can set directly in your form the desired second value
<form method="POST">
<input name="imagekey" type="hidden" value="<?php echo $row_images['key']; ?>">
<input name="imagekey2" type="hidden" value="<?php echo ($row_images['key'] - 1); ?>">
</form>
and now assign to a variable
$colname_images2 = $_POST['imagekey2'];

PHP random text once

I've been looking for the solution of my problem for ages and I still haven't found it so i desided to create a stackoverflow account to ask the question myself.
this is what I created so far:
<? //Chooses a random number $num = Rand (1,2);
switch ($num){
case 1: $retrieved_data = "test"; break;
case 2: $retrieved_data = "test1"; break;
} ?>
And this is the place where I want the text to appear;
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input name="<?php echo $retrieved_data; ?>" type="file" />
<input name="<?php echo $retrieved_data; ?>" type="file" />
<input type="submit" value="Upload" /></form>
My problem is I want to have the "test1" and "test" randomly displayed on these places
but I want them to be different from eachother every time. So if the first input type is "test" I want the second input type to be 'test1" but I can't seem to get this working
Does anyone know what I'm doing wrong or a code to make this possible?
If you have limited number of possibilities, put them int an array, shuffle it and shift/pop elements from it:
$retrieved_data = array('test', 'test1');
shuffle($retrieved_data);
$random1 = array_shift($retrieved_data);
$random2 = array_shift($retrieved_data);
Step A - you are selecting a number, 1 or 2
Step B - you are running that number through your switch case, this case ONLY takes the number that it receives and assigns it a value. Therefore if your number is 1, your switch case ends at $retrieved_data = "test". If your number is 2 your switch case goes to case 2 and assigns $retrieved_data = "test 1".
Step C = $retrieved_data is assigned to your form (it will have only one value, "test" or "test1".
Use array_rand() for that.
$aName = array('test1', 'test2', 'whatever');
function getRandom(array &$aName)
{
if (($key = array_rand($aName)) === NULL) {
throw new Exception('No more randomness!');
}
$value = $aName[$key];
unset($aName[$key]);
return $value;
}
So simply use getRandom($aName) when you need a unique random item from the array.

Help with a function php

I want a function that prints those 2 "print" in the database ( insert intro ) when a button is pressed.
Here's the code:
<?php
$id2name=array();
$x=mysql_query("SELECT id,name FROM products WHERE id IN(".implode(',',array_keys($_SESSION['cart'])).")");
while($y=mysql_fetch_assoc($x)){
$id2name[$y['id']]=$y['name'];
}
foreach($_SESSION['cart'] as $k=>$v){
print "<br>[".$id2name[$k]."]\t".$v."\n <br>";
}
print "<br>$total<br>";
?>
How can I make that a function, to print it in the database when a button is pressed?
Not sure if I got you right, but as far as I understand, you want to write something to the database by pressing a button, right?
Well, to trigger an action by pressing a button, you need a form:
<form action="page_to_process_the_db_request.php" method="post">
<input type="hidden" value="<?php echo $total;?>" name="total" />
<input type="submit" value="Wirite to DB!" />
</form>
In this example, I assume you want to write the variable $total to DB.
So you post the data to the processing page (which also can be the same one you're on) and there, you look if there's something in the $_POST-array:
<?php
if(isset($_POST['total'])) {
mysql_query("UPDATE products SET total = ". $total); //or something like that
}
?>
Not sure though if this is what you're looking for...
//edit
referring to your comment, I guess you want to write the output of the loop to DB...
At first, you have to create an appropriate structure, like an array:
foreach($_SESSION['cart'] as $k=>$v){
$id2name[$k]['name'] = $v;
}
now you can turn the array into a simple string with
$serialized_array = serialize($id2name);
And now you can write this string to db. And when you read it from db, you can turn it back into an array again with:
$id2name_array = unserialize($serialized_array);

Categories