I have been trying to do this for a few days, and I cant seem to find anything on the net about it, but then again I am not really sure what I should be searching, plus it may not even be possible.
So I have a form which is looped dependent on how many parcels they wish to send, I loop the names using the index in the loop, as you can see below. so it goes like 'Weight . $i' = 'Weight1' and so on...
I then stores these into session variables, but now I want to pull through all the session variables for those that are set, and I wanted to be able to loop through the session variables as I am trying to display like a summary page of all the parcel details, as shown in below code?
I have sessions called PWE1, PWE2 etc and want it to loop through them rather than calling them individually.
Is this possible? if so how?
<h4>Parcel Details</h4>
<?php
if($SV != null){
$i = 0;
do {
$i++;
?>
<h3>Parcel <?php echo $i;?> </h3>
<p> Weight: <?php echo $_SESSION['PWE' . echo $i ]; ?> </p>
<?php
} while ($i != $SV);
}
?>
Why not use a 2d array and loop through it?
// store your PWE1, PWE2 etc in here
$_SESSION["weights"]["PWE1"] = $value;
$_SESSION["weights"]["PWE2"] = $value2;
$_SESSION["weights"]["PWE3"] = $value3;
$i = 0;
foreach($_SESSION["weights"] as $pwe) {
echo '<h3>Parcel' . $i . '</h3>';
echo '<p>Weight:' . $pwe . '</p>';
$i++;
};
Related
I have a form that has several input types all that need to be a handled differently. I did a loop to name them like so in the form:
product-0-length
product-0-size
product-1-length
product-1-size
product-2-length
product-2-size
On my processing php (where the form info gets sent) I want to iterate a loop to handle say size different from length. My thought was this but no luck:
<?php
$i = 0;
foreach($_REQUEST['product-'.$i.'-length'] as $key => $val) {
//style or do what I need with the length information for each product
echo '<li>'.$key.'='.$val .'</li>';
$i++;
}
?>
As I suggested in the comments above you could use a different naming scheme for your input fields. Take a look at this example for the form creation:
<?php
foreach ($i=0; $i<3; $i++) {
echo "<input type=\"text\" name=\"product[$i][length]\">\n";
echo "<input type=\"text\" name=\"product[$i][size]\">\n";
}
When submitting this form the server will translate the notation into a php array which is a very convenient thing. You can simply iterate over that array:
<?php
foreach ($_POST['product'] as $key=>$product) {
echo "<li>Length of product $key: " . $product['length'] . "</li>\n";
echo "<li>Size of product $key: " . $product['size'] . "</li>\n";
}
Note that this is a very primitive example, all error checking and the like is missing to keep things crunch. Also I did not test this code here, it is just meant to point you into the right direction, but I hope there are not too many typos in there...
I am trying to store the values of selected checkboxes on a multi page form so I can include these on the final page of the form (and in the email that is sent to the site owner).
I have worked out how to display the values, but saving them for later has got me stumped. I'm learning as I go so I wouldn't be surprised if this is quite easy...
This is the code I'm using:
<?php foreach ($_POST['fooby'] as $key => $entry) {
if(is_array($entry)){
print $key . ": " . implode(',',$entry) . "<br>";
}
else {
print $key . ": " . $entry . "<br>";
}
} ?>
And this is the result I get:
1: Minor Service £129
2: plus MOT £35
That's exactly what I'm after - though I don't need the numbers at the beginning. How do I save that information for later?
With the updated code below, I now get the following result:
Minor Service £129
plus MOT £35
That's perfect, but I'm struggling to work out how to store that information to a session variable. I should point out that the values returned from the form are dynamic and unknown beforehand. There might also be 10 items in the array, not just the two shown above.
What I have so far:
<?php if (isset($_POST['fooby'])){
foreach ($_POST['fooby'] as $entry) {
if(is_array($entry)){
$dokval = implode(',',$entry) . "<br>";
echo $dokval; //echoes the expected result on the page
$_SESSION['dokvalues'] = $dokval; //only stores the last item
}
else {
print $entry . "<br>"; //not rewritten this part yet
}
}
} ?>
Simply insert these values in hidden input elements in a form on the following pages to use them again:
<input type="hidden" name="<?php echo $key1; ?>" value="<?php echo $value1; ?>" />
<input type="hidden" name="<?php echo $key2; ?>" value="<?php echo $value2; ?>" />
...
The foreach loop iterates through the array and for each iteration $key variable is the current index and $entry is the value of that index. The numbers in the list are just representation of index values. If you don't need them, you can go for this:
<?php foreach ($_POST['fooby'] as $entry) {
if(is_array($entry)){
print implode(',',$entry) . "<br>";
}
else {
print $entry . "<br>";
}
} ?>
The keys will still stay in $_POST['fooby'] array.
The variable $entry holds one value of the array each time the foreach loop iterates. So the variable $dokval will also hold only one value, which it echos each time the loop iterates. By the time you look at the session variable it's value is going to be the last value that $dokval held. Make $dokval an array and push the $entry value into it. array_push. Also, make sure you start a session at the beginning of every page you want to use the $_SESSION variable.
Jeff
I've been learning PHP in my spare time, and this is one of my "Hello, World" type scripts I'm doing for practice.
This is the code below, and the default strings will not change so the code will end up looping into eternity for I have no idea why:
<?php
if (isset($_POST["pbankroll"], $_POST["pstartbet"]))
{
$bankroll = $_POST["pbankroll"];
$startBet = $_POST["pstartBet"];
//If using this code below instead of that above, everything will work fine:
//$bankroll = 200;
//$startBet = 25;
while($bankroll >= $startBet)
{
$evenOrOdd=mt_rand(0,1);
if ($evenOrOdd == 1)
{
$bankroll += $startBet;
echo "Win ...... Bankroll is now: " . $bankroll . "<br>";
}
else
{
$bankroll -= $startBet;
echo "Loss ..... Bankroll is now: " . $bankroll . "<br>";
}
}
echo "Probability, the Devourer of all Things!";
}
else
{
echo "Please enter a bankroll and starting bet above.";
}
?>
The form to it:
<form action="index.php" method="post">
Bankroll: <input type="text" name="pbankroll">
Start Bet: <input type="text" name="pstartbet">
<input type="submit">
</form>
I appreciate the help.
The HTML name pstartbet needs to be changed to pstartBet.
Edit to clarify:
The Start Bet input element in the HTML form has the name pstartbet with the 'B' in lowercase. When PHP checks for that value, it's looking for pstartBet with the B capitalized. One of these two names needs to be changed so the cases match.
As it is:
$startBet = $_POST["pstartBet"]; // doesn't exist
This means that $startBet will be null. When cast to a number by the mathematical operations this will result in 0 - so the value of $bankroll will never change, and the loop will continue forever.
First, you'll have to convert the incoming values to integer before using them in numerical operations:
$bankroll = intval($_POST["pbankroll"]);
$startBet = intval($_POST["pstartBet"]);
Or if they are float values use:
$bankroll = floatval($_POST["pbankroll"]);
$startBet = floatval($_POST["pstartBet"]);
Beside from this, the code can of course run forever. This is because of the pseudo randum numbers that are being used. If over a long time there are more 1's then 0's generated by mat_rand() then the code will run forever
Consider that truly random numbers cannot be generated by a computer. Apparently mt_rand generates a pseudo-random number in such a way that it's causing an infinite loop.
I would recommend setting the variables outside of the if clause & setting a default of '' which basically means 'empty' & then having the if check if those two variables are empty or not.
<?php
$bankroll = array_key_exists("pbankroll", $_POST) ? intval($_POST["pbankroll"]) : '';
$startBet = array_key_exists("pstartbet", $_POST) ? intval($_POST["pstartbet"]) : '';
if (!empty($bankroll) && !empty($startBet))
{
//If using this code below instead of that above, everything will work fine:
//$bankroll = 200;
//$startBet = 25;
while($bankroll >= $startBet)
{
$evenOrOdd=mt_rand(0,1);
if ($evenOrOdd == 1)
{
$bankroll += $startBet;
echo "Win ...... Bankroll is now: " . $bankroll . "<br>";
}
else
{
$bankroll -= $startBet;
echo "Loss ..... Bankroll is now: " . $bankroll . "<br>";
}
}
echo "Probability, the Devourer of all Things!";
}
else
{
echo "Please enter a bankroll and starting bet above.";
}
?>
$i=0;
while (db_data) {
$i++;
echo '<input type="checkbox" name="v['.$i.']" value="'.$url.'"';
if ($v[$i]) {
echo ' checked';
$s .= $url;
}
echo '/>';
}
I have the above array of checkboxes. It worked on my pc, but not on the server; it seems like the confusing part is on $v[$i].
$v is not defined, but sure used no where else. the problem is my checkbox selection never restored, and code never get into the if statement.
however, if i add the following, i can see the value. just the checkbox lost after the processing
$v=$_POST['v'];
while (list ($key,$val) = #each ($v)) {
$x .= ' 11*'.$key.'-'.$val.'*22 ';
}
my goal is to preserve the checkbox checked on the form, and i need the $s elsewhere. any solution to replace $v[$i]?
Can anybody help me fix this? Thank you.
The issue seems to be $v = $_POST. If you are just doing that then your conditional statement would need to be
if ($v['v'][$i]) {
///Checkbox
}
or just do $v = $_POST['v'].
Sorry, ignore above as you did mention you did that part. See below.
Here is working code.
<form action="" method="post">
<?php
$v = $_POST['v'];
$i=0;
while ($i < 4) {
$i++;
$url = "test.com/".$i;
echo '<input type="checkbox" name="v['.$i.']" value="'.$url.'"';
if ($v[$i]) {
echo ' checked="checked"';
$s .= $url;
}
echo '/> '.$url.'<br />';
}
?>
<input type="submit" name="submit" value="submit" />
</form>
I left the code pretty much the same to show you where you went wrong, but you should be checking the $_POST variable for exploits before using. If I were doing this as well, I would use a for count, but it's setup as a placeholder for your database code. Make sure that $url gets populated as well.
You could also do away with the $i variable like:
<?php
$v = $_POST['v'];
while (db_data) {
echo '<input type="checkbox" name="v[]" value="'.$url.'"';
if (is_array($v)) {
if (in_array($url,$v)) {
echo ' checked="checked"';
$s .= $url;
}
}
echo '/> '.$url.'<br />';
}
?>
Try to print_r($_POST) and then print_r($v) and see if anything comes up. If the $_POST works, then you know that it is being posted back to the page correctly. Then if the $v is working, then you know you set $v = $_POST correctly. Due to the fact that you don't actually give us any information on the db_data, I assume this is working correctly and displaying all the checkboxes on first load, so as long as it is posted and you are setting the $v variable, it should be working.
A side note is that you should validate the $_POST variables before using, but do that after you get things working.
change
name="v['.$i.']"
to
name="v[]"
the fact that PHP picks that up as an array is a unintended feature of PHP that wasn't intentionally designed. you don't need to set the indexes, just define it as an array.
I have a 2 field database (daynumber & datavalue), the data of which I am retrieving with php then creating and passing variables into jquery for use with a graph.
I am not doing this as an array because I need to apply a formula to the datavalue field. The formula can be altered by the user.
In jquery, I need to be able to do this:
cday_1 = <?php echo $day_1?>;
cday_2 = <?php echo $day_2?>;
tday_1 = (<?php echo $day_1 ?> * formula1 / formula2;
tday_2 = (<?php echo $day_2 ?> * formula1 / formula2;
The cday series and the tday series will be plotted separately on the graph.
My problem is that I could manually name each var in php, ie:
$day_1=mysql_result($result,$i,"datavalue");
but I have 30 rows and I'd prefer to do it with a loop. So far, I've got this far:
$i=0;
while ($i < $num) {
$datavalue=mysql_result($result,$i,"datavalue");
echo "\$day_";
echo $i;
echo " = ";
echo $datavalue;
echo "<br>";
$i++;
}
So there are a couple of problems I'm having with this.
The first problem is that while everything is echoing, I'm not sure how to actually create variables like this(!).
The second problem is that there are only 30 rows in the db, but 34 are actually outputting and I can't work out why.
I'm self-taught, so apologies for clumsy coding and/or stupid questions.
You could just store them in a PHP-side array:
$days = array(
'cday' => 'the cday value',
'dday' => 'the dday value',
etc...
);
and then via json_encode() translate them to a Javascript array/object automatically. This object could be sent to your page as an AJAX response, or even embedded into the page directly:
<script type="text/javascript">
var days = <?php echo json_encode($days) ?>;
</script>
after which you just access the values as you would any other array in JS.
Have ended up doing this:
$i=0;
while ($i < $num) {
${"day_$i"}=mysql_result($result,$i,"datavalue");
$i++;
}
I have a feeling this was a basic issue and I just didn't explain myself properly. I am unable to use an array as I needed to fiddle with formulas so this solution worked fine.