In a bit of a while loop mess! - php

I have spent quite some time making a function and the last 15-20 minutes trying to figure this out. I need help!
I am selecting multiple rows from the database and then running them in a while loop.
They are available on a dropdown menu.
<form method="POST" action="adminprocess.php">
<fieldset>
<p>
<label class="left2">League:</label>
<select name="league" class="combo">
<?php
$q = $database->selectAllLeagues();
while($row=mysql_fetch_assoc($q))
{
$theid = $row['id'];
extract($row);
?>
<option value="<? echo $theid; ?>">
<? echo $format.'_'.$game.'_'.$name.'_Season '.$season;?>
</option>
<?
}
?>
</select>
</p>
<p>
<input type="hidden" name="replaceleague" />
<input type="hidden" name="format" value="<? echo $format; ?>" />
<input type="hidden" name="game" value="<? echo $game; ?>" />
<input type="hidden" name="name" value="<? echo $name; ?>" />
<input type="hidden" name="season" value="<? echo $season; ?>" />
<input type='submit' class="button" value='Select league' />
</p>
</fieldset>
</form>
$theid seems to be working fine dependning on which row i select on the dropdown menu.
However, I cant get the values below in the hidden inputs to pass through the correct values from the row selected in the dropdown box.
It seems to always pass through the 4 variables from the first row of the database.
So basically, I need it to select the right row and use that data.
What am i doing wrong!!!
Thanks for reading!

Your hidden fields are initialized outside the loop, so they'll use the values that were left over from the last iteration of the while loop. (i.e. the last fetched row)
Why do you actually need the hidden fields in the first place? When you submit the form, the league field will contain the ID of the row selected in the drop-down box. Using the ID, you can fetch the other fields from the database when processing the form.

To directly answer your question about the while loop, it's because the hidden inputs are echoed outside the loop, after which data the last-iterated row from your database is used by PHP to output to those hidden inputs.
But I suggest that instead of using hidden form elements like that, you submit your form with the <option> with the value a user chooses, read the value (as in $_POST['league']), and fetch the row from your database with that ID and use it accordingly. (You may wish to keep the replaceleague hidden input if your application needs it of course.)
It's much easier, plus it ensures the information about the row a user chooses is coming from your database and not tampered with. In fact, for most applications this is the right way to go.

Related

PHP foreach executing code multiple times

At the bottom of this code you'll see an 'Accept Offer' button, when I click on that another piece of code gets executed as you can see on the bottom of this post.
For example this project has 3 bidders, so 3 times bidder_id and writer_bid so I use 'foreach' and load it in divs, works fine, but now I need to store those variables in a database, which technically works but it doesn't store the bids from the row I pull them from, it just takes the data from the last row, that is if I place the code at the bottom of this thread in my header.
However when I put it inside the loop it executes three times, I saw that when I got an error message that I had to close 3 times cause there are 3 rows in the database table that I pull the data from.
How can I prevent this, and either have it load once when the code is inside the foreach loop, or have it pull the correct writer_bid and bidder_id to store.
<div class="WB-Bottom-block lefts">
<?php $getBidders=" AND project_id=$project_id"; $bidders=getBidder($getBidders); foreach($bidders as $bidder) {
$bidder_id=$bidder['writer_id'];
$writer_bid=$bidder['writer_bid'];
?>
<div class="findwriters_boxes">
<div class="findwriters_right">
<div style="float:right;margin-top:6px;width:170px;">
<input type="hidden" name="writer_bid" id="writer_bid" value="<?php echo $writer_bid; ?>" />
<input type="hidden" name="bidder_id" id="bidder_id" value="<?php echo $bidder_id; ?>" />
<input type="submit" class="homebtn11" name="submit" id="submit" value="Accept Offer"/>
</div>
</div>
</div><?php } ?>
Below the code that needs to be executed and that results in issues, whether I place it inside the foreach loop, or inside the header instead.
As you can see I tried to store it in input fields so that it stays there so the header can pull it on refresh of the page / click of the button.
<?php if(isset($_POST['todo']) && $_POST['todo']=='submit_project') {
$balance=get_client_balance_info($current_user->ID);
$writer_bid=$_POST['writer_bid'];
$bidder_id=$_POST['bidder_id'];
if($balance >= $_POST['writer_bid']) {
global $wpdb;
$sql3="UPDATE `wp_project` SET `writer_id` = '".$bidder_id."' WHERE `id` =". $project_id;
$wpdb->query($sql3);
$sql4="UPDATE `wp_project` SET `price` = '".$writer_bid."' WHERE `id` =". $project_id;
$wpdb->query($sql4);
$sql5="UPDATE `wp_project` SET `status` = '2' WHERE `id` =". $project_id;
$wpdb->query($sql5);
$success_msg="You accepted a bid, the money will be deducted from your account.";
}
else $fail_msg="Your balance is not sufficient.";
I think you should make a form for each div that you are adding right now you are putting the bidder_id in the different inputs but the same name.
So it will get the last inputs, maybe it's better to specify the inputs with the row id or to separate the forms or make the input names as array.
I hope this helps you.
I fixed it with the help of Diar Selimi like this:
<div style="float:right;margin-top:6px;width:170px;">
<form action="" name="frmeditor" method="post" id="frmeditor" >
<input type="hidden" name="todo" id="todo" value="submit_project" />
<input type="hidden" name="writer_bid" id="writer_bid" value="<?php echo $writer_bid; ?>" />
<input type="hidden" name="writer_id" id="writer_id" value="<?php echo $writer_id; ?>" />
<input type="submit" class="homebtn11" name="submit" id="submit" value="Accept Offer"/>
</form>
Before that my form and value="submit_project" tags were scattered all over the place!

Returning only the last value of query

This is my second code but the problem is I have 3 queries. So it only returns the last product_id when i Click update it always return product_id=3, but i want update the product_id=2
<form action="update_qty.php" method="POST">
<?php while($getorder = mysqli_fetch_array($order)){ ?>
<input type="hidden" value="<?=$getorder['price']?>" name="actual_price">
<input type="hidden" value="<?=$getorder['product_id']?>" name="product">
<input type="text" value="<?=$getorder['qty']?>" name="qty" size="1" style="text-align:center">
<input type="submit" value="update" name="update">
<?php } ?>
</form>
Your problem is that the PHP is server side and you need something client side to read the value of the text box. You would need a page refresh to pass the text field value to the server so it could write it to the url in the anchor tag. Which is what the form submit would do, but as it would have submitted the value already the anchor tag would be pointless
To do it without a page refresh use Javascript. It would be easy to do with jQuery. You could add an event that writes whatever is entered in the text box the the anchor tags href as it is typed.
I'll do something more like this.
One form per product.In your case when you submit the form the qty value will always be the las found.
<?php while($getorder = mysqli_fetch_array($order)){ ?>
<form action="update_qty.php" method="POST">
<input type="hidden" value="<?=$getorder['price']?>" name="actual_price">
<input type="hidden" value="<?=$getorder['product_id']?>" name="product">
<input type="text" value="<?=$getorder['qty']?>" name="qty" size="1" style="text-align:center">
<input type="submit" value="update" name="update">
</form>
<?php } ?>
You can add more information like this
update
You can not get all values as like that because input name overwrite in every loop iteration.
For multiple values you can try in two ways like:
<?php
while($getorder = mysqli_fetch_array($order)){
$newArr[] = $getorder['price']."~".$getorder['product_id']."~". $ getorder['qty'];
} //while end
?>
<input type="hidden" name="allinputs" value="<?=$newArr?>">
Input field outside the loop.
In php explode array value with ~ and get the all values.
Other solution is that
Your input field name must be change like:
<?php while($getorder = mysqli_fetch_array($order)){ ?>
<input type="hidden" value="<?=$getorder['price']?>" name="actual_price_<?=$getorder['product_id']?>">
<?php } ?>
Change field name in every iteration.
In current scenario either you need three different buttons or the best solution to use AJAX request .
update
On update_qty.php u can use like this
<?php echo $_GET['product_id'];?>

PHP foreach loop, need loop to get data from db, but it is also looping my forms

So I have a categories table in my database and each category has a certain amount of steps assigned to it. I want to have all of the categories displayed as tabs titled with the category name so I need this from the database. I then have a form inside the tabs to insert the amount of steps needed for that category, but this form is looping... I need it inside the foreach to get the category id but without the form looping... Hope that makes sense..
Here is my code:
<?php foreach($categories as $category){ ?>
<div id="<?php echo $category->category ?>" class="tab">
<form id="maxSteps" method="POST" name="maxSteps" action="<?php $PHP_SELF; ?>" enctype="multipart/form-data">
<label for="maxSteps">Amount of steps in form: </label><input style="width:50px;" id="maxSteps" type="text" name="maxSteps" />
<input type="hidden" name="catId" value="<?php echo $category->cat_id; ?>" />
<input type="Submit" value="Go" name="maxStepsSubmit" />
</form>
<table id="amountOfStepsForm">
<?php $maxStepsById = $wpdb->get_results( "SELECT * FROM metal_work_max_steps WHERE cat_id = '$category->cat_id'" ); ?>
<?php foreach($maxStepsById as $maxStep){ ?>
<tr><td id="maxStepsRow<?php echo $maxStep->id; ?>"><?php echo "<p>Amount of steps in form is: <b>".$maxStep->steps."</b>" ?></td><td id="editRow<?php echo $maxStep->id; ?>"><a id="<?php echo $maxStep->id; ?>" class='edit'>Edit</a></td></tr>
<input type="hidden" name="catId" value="<?php echo $category->cat_id; ?>" id="catId<?php echo $maxStep->id; ?>" />
<?php } ?>
</table>
</div>
<?php } ?>
Regards
The best thing you can do is to run only one query and retrieve all your data inside an associative array. Then just loop trough this data structure.
The query can be done using a JOIN statement, in order to retrieve the information regarding the max steps for each category.
1- put the Form tag above the for loop
2- <input type="hidden" name="catId" val... need to have dynamic name: name="catId_<?php echo $category->cat_id;?>"
3- the button Submit label GO, and the colse tag of Form need to be out of the for loop (below)
so all the fields will be in 1 form,
and you will have 1 submit button, if that what you need,
and the field names are not the same, so on submit you can read all of them
these are general comments, i think you need to pay attention to.

onClick - selected (clicked) value in input box

i am retrieving data form database using a search query.
PHP code (which I'm using in search query to display search results)
echo "<span style='background-color= #FFFF00'>$query</span><br>";
$count=$dbo->prepare($query);
$count->execute();
$no=$count->rowCount();
if($no > 0 ){echo " <span>No of records = ".$no."</span>";
echo "<table><tr><th>PHONE NUMBER</th><th>OWNER NAME</th></tr>";
foreach ($dbo->query($query) as $row){
echo "<tr><td>$row[ROLLNO]</td><td>$row[CNAME]</td></tr>";
}
echo "</table>";
i want to do like this,
when a user clicks on a phone number, it should redirect to a new page and in that new page, my input box should be filled with this phone number and should be submitted.
Input Box Code (which I'm using in page 2)
<form name="phone_number_form" id="phone_number_form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" onsubmit="return vali()" >
<input type="text" name="number" id="number" />
<input type="submit" name="submit" value="Submit" />
</form>
Looking at w3schools PHP has a $_POST variable which is used to collect values from a form sent with method="post". There's also $_GET and $_REQUEST which seems to merge both post and get data. http://www.w3schools.com/php/php_post.asp
There are a couple of options like making a request (get) from your first page or post the data from your first page.
REQUEST Method
Heres how I think the request way to do it would work
PAGE 1
Amend the foreach that renders the table row to include an hyperlink to your second page
foreach ($dbo->query($query) as $row){
echo "<tr><td>$row[ROLLNO]</td><td>$row[CNAME]</td></tr>";
}
PAGE 2
Amend the textbox to be populated with the phone number from the request variable
<input type="text" name="number" id="number" value="<?php echo $_REQUEST["phoneno"]; ?>" />
POST Method
In your first page using javascript when the user clicks the phone number set a hidden field and submit the form to the second page. Again you should be able to read the hidden fields value from the $_REQUEST variable

kohana parse $_POST data

i have a kohana application, and i have a form with several checkboxes, and the user is supposed to check his preferences there in the form. so i have a relation 1:n between the user table and the preferences table. my problem is that i want to save those preferences, selected in the form, and i don;t know how.
i have the form:
<form id="address" method="POST" action="<?= Route::url('Save user preferences' , array('user_id' => $user));?>">
<? foreach ($prefered_products as $pp): ?>
<input type="checkbox" name="user_preferences_preference[]" value="<?= $pp ?>" /><?= $pp->product; ?><br />
<? endforeach; ?>
<button type="submit">Salveaza preferintele tale</button>
</form>
and i save the data:
foreach ($_POST['user_preferences_preference'] as $up) {
$user_preferences->prefered = $up;
$user_preferences->user = $this->user;
$user_preferences->save();
}
$this->view->message = __('Thank you for your feedback!');
but seems like the way i parse the preferences is not correct, i am getting: ErrorException [ Warning ]: Invalid argument supplied for foreach()
any idea about how am i supposed to get the multiple $_post preferences?
thank you!
I have a slightly different way of doing this.
When I create a checkbox I also create an identical hidden field set to zero
<input type="hidden" name="my_check" value="0" />
<input type="checkbox" name="my_check" value="$value" />
The checkbox, if ticked, will override the hidden value. This way when you send the form you end up with $_POST['checkbox]=1 or 0, but it always exists in the $_POST.
The nice thing about this method is you can extend the Form::checkbox helper so that it's always present and you don't have to worry about it for every form / controller.
p.s. in you above example you would probably want to do it like this:
<input type="hidden" name="user_preferences_preference[$pp->id]" value="0" />
<input type="checkbox" name="user_preferences_preference[$pp->id]" value="<?= $pp ?>" />
<?= $pp->product; ?><br />
Or use a $key value instead of $pp->id.
The problem is that a checkbox will only post data when set. You should reverse check the values. Ie;
Fetch all preference (id's) from the database
Check if a value is found in the $_POST var
If not, update to false (or 0 or whatever) in db, if set, read out the value.

Categories