PHP Checkbox Values - php

I'm trying to create a checkout page in PHP. The page that lists the items is called shop.php. On this page, I display a number items to be sold with a checkbox beside each item. I'm pulling the item name and price information from the database. Here's my main code.
$row = mysql_fetch_array($query);
while($row) {
echo "<TR>";
echo "<TD><B>$row[Name] </B></TD>";
echo "<TD><B>"."$"."$row[Price] </B></TD>";
echo "<TD><input type=checkbox name=foods[] value='$row[Price]' /></TD>";
echo "</TR>";
$row = mysql_fetch_array($query);
}
<input type="submit" name="buy" value="Buy Now" />
So I am setting the name of the checkboxes to foods[] which'll be an array that'll contain values of all checkboxes submitted. When the user clicks on the "Buy Now" button, they'll be redicted to the cart.php page, that'll display the name and price of the item they've purchased. I know that I can output the prices by looping through the $items array. The problem I have is that I don't understand how would I display the item names. I thoght of doing the following:
$row = mysql_fetch_array($query);
while($row) {
echo "<TR>";
echo "<TD><B>$row[Name] </B></TD>";
echo "<TD><B>"."$"."$row[Price] </B></TD>";
echo "<TD><input type=checkbox name='$row[Name]' value='$row[Price]' /></TD>";
echo "</TR>";
$row = mysql_fetch_array($query);
}
This time, both the name and the price of the items are included in the checkbox as its name and value. But again, the problem is how would I display them on the cart.php page without hard coding. What I means is that how would I display the item name and its price without doing something like this:
(Assume that one of the items name is Burger which was populated as the name of the checkbox.)
if (isset($_POST['Burger'])){
echo "<td>$_POST['Burger']</td>";
}
I'd appreciate any suggestions/tips on this question. Thank you.

If you name the checkboxes like:
<input type='checkbox' name='foods[{$row['Name']}]' value='{$row['Price']}' />
You can access the array $_POST['foods'] and the key/value will be Name/Price. So you can do:
foreach($_POST['foods'] as $name => $price) {
echo "<tr><td>$name</td><td>$price</td></tr>";
}

Set name to each checkbox as foods[$row[name]]. You should have following code:
$row = mysql_fetch_array($query);
while($row) {
echo "<TR>";
echo "<TD><B>$row[Name] </B></TD>";
echo "<TD><B>"."$"."$row[Price] </B></TD>";
echo "<TD><input type=checkbox name='foods[{$row[Name]}]' value='$row[Price]' /></TD>";
echo "</TR>";
$row = mysql_fetch_array($query);
}
<input type="submit" name="buy" value="Buy Now" />
On POST you will have associated array of item names and prices.

Related

Php form array not passing values to other pages

I am working on a project where I want users to choose their space for parking and book it. I have a MySQL database which holds information about parking slots. I am fetching those values and display it using table and form. I have put checkboxes to make choice. and once they make choice they should be directed to payment page.
I am having problem with checkbox. I can see that in value fields it has values from database but when I hit submit button it doesn't pass any values to next page.
below is my code
<body>
<form method="POST" action="book.php">
<?php
//we create a table
echo "<table>";
// create table th
echo "<tr > <th> Parking Slot No </th> <th> Status </th>";
$sql=" select ParkingSlotNo,Status from fleming_dwing ";
$st=$conn->prepare($sql);
$st->execute();
$total=$st->rowCount();//get the number of rows returned
if($total < 1 ){//if no row was returned
echo "<tr> <td style> No Data: DataBase Empty </td> ";//print out error message
echo "<td> No Data: DataBase Empty </td> ";//print out error message
$ing = "<img src='img/occupied.png'/>" ;
}
else{
while($res = $st->fetchObject()){//loop through the returned rows
echo "<tr>";
if($res->ParkingSlotNo and $res->Status=='OCCUPIED')
{echo "<td> $res->ParkingSlotNo </td> ";
echo "<td> <img src='img/occupied.png'/> </td>";
echo"<td><a href=''> </a> </td>";
}
else
{
echo "<td> $res->ParkingSlotNo </td> ";
echo "<td> <img src='img/vacant.png'> </td>";
echo"<td><input type='checkbox' value='$res->ParkingSlotNo'></td>";
}
echo"</tr>";
}
}
?>
</table>
<input type="submit" value="Submit">
</form>
</body>
</html>
and this is the code for booking page
<?php
require_once("dbconfigpdo.php");
print_r($_POST);
?>
The checkboxes do not have name attributes. A form control can't be successful (included in the name=value pairs of data that are submitted) without one.
Any input must have a name attribute.
By name you can use a value. So, you need to add name="your name" to your checkboxes.
You need to set an attribute name to your input field, or it will not be processed.
Something like:
<input name='parkingslot' type='checkbox' value='$res->ParkingSlotNo'>

Getting the value of an array derived from a table

I have a list of products the secretary can choose. These products are looked up from the product table and an array was used to display them.
The secretary can select up to any number of the products by checking the checkboxes corresponding to the product. When submitted, the checked products are then displayed in a new page.
Supposedly, the secretary would be able to input the amount of boxes, weight, date of production, and price for each selected product. As I have to insert the information to the table, I'm wondering how I'll be able to do it with an array whose value is not know to me. I've seen examples of inserting arrays into tables, but not arrays that were derived from a table.
EDIT: Added in the code.
$products = $mysqli->query("SELECT ProdName FROM product");
$numofprod = mysqli_num_rows($products);
$i = 0;
while($i < $numofprod) {
while($row = $products->fetch_assoc()){
$prodlist = $row["ProdName"];
echo "<input type='checkbox' class='prodlist' name='check_list[]' id='prodlist";
echo "$i'";
echo " value='";
echo $prodlist;
echo "'>";
echo $prodlist;
echo "</input>";
$i++;
}
}
// upon submitting, it will execute the code below
if(isset($_POST['add_purchase_submit'])){//to run PHP script on submit
if(!empty($_POST['prodlist'])){
echo "<table><tr><th></th><th> Boxes </th> <th> Weight </th> <th> Price </th> <th> Production Date </th> </tr>";
// Loop to store and display values of individual checked checkbox.
foreach($_POST['prodlist'] as $selected){
echo "<tr><td>";
echo $selected;
echo "</td><td>";
echo "<input type='text' name='ppbox' size='10'>";
echo "</td><td>";
echo "<input type='text' name='ppweight' size='10'>";
echo "</td><td>";
echo "<input type='text' name='ppprice' size='10'>";
echo "</td><td>";
echo "<input type='text' name='ppproducion' size='15' placeholder='MM/DD/YY'>";
echo "</td><td></tr>";
}
}
}
I also realized I have an error in the names in the second form...
for($i = 0; i < array.size(); i++){
echo '<input name="array['.$i.']"'>;
}
This gives an amount of inputs abed on you array. Later you can read that as a array in php again:
foreach($_POST['array'] as $entry){
.. do things ..
}
Only a basic scatch, but this shows how you can use arrays as names for inputs. The same way you could use them for checkboxes or other felds you need.

the form clears the array everytime I send it

I have a form with 2 selects, when you send the first, the second select charges the values that are called on my oracle bd with a query, then when i send the second select, it generates a table with checkboxes:
if(isset($idTActi)){
$stallTableTarifas=oci_parse($conn, "SELECT TARIFAS.ID, TARIFAS.ID_TIPO_ACTIVIDAD, TARIFAS.TIPO, TIPO_ACTIVIDAD.TEMPS_KM, TARIFAS.PRECIO
FROM TARIFAS, TIPO_ACTIVIDAD
WHERE TARIFAS.ID_TIPO_ACTIVIDAD = TIPO_ACTIVIDAD.ID
AND TARIFAS.ID_TIPO_ACTIVIDAD = $idTActi");
oci_execute($stallTableTarifas);
echo "<div class='divPrecios'>";
echo "<table>";
echo "<tr class='tabPreciosTitles'>";
echo "<td>Tipus Tarifa</td>
<td>Temps/Km</td>
<td>Preu</td>
<td><input type='submit' class='carrito' value=''></td>";
echo "</tr>";
while (($row=oci_fetch_array($stallTableTarifas,OCI_BOTH))!=false){
echo "<tr>";
echo "<td>".$row['TIPO']."</td>";
echo "<td>".$row['TEMPS_KM']."</td>";
echo "<td>".$row['PRECIO']."</td>";
echo "<td><input type='checkbox' name='checkbox[]' value='".$row['ID']."'/></td>";
echo "</tr>";
}
echo "</table>";
echo "</div>";
}
echo "</form>";
The variable $idTActi it's the id that i return from the second select, so when i click on the checkboxes and i send it on the button named class='carrito', that's an sprite that i generate on css, i see on the bottom another table with the information that i selected on the previous table:
echo "<div class='divPrecios'>";
echo "<table>";
echo "<tr class='tabPreciosTitles'>";
echo "<td>Nom Activitat</td>
<td>Nom Tipus Activitat</td>
<td>Tipus Tarifa</td>
<td>Temps/km</td>
<td>Preu</td>";
echo "</tr>";
foreach($_POST['checkbox'] as $item){
$stallTableCarrito=oci_parse($conn, "SELECT ACTIVIDAD.NOM AS NOM_ACTIVIDAD, TIPO_ACTIVIDAD.NOM AS NOM_TACTIVIDAD, TARIFAS.TIPO, TIPO_ACTIVIDAD.TEMPS_KM, TARIFAS.PRECIO
FROM TARIFAS, ACTIVIDAD, TIPO_ACTIVIDAD
WHERE TARIFAS.ID = $item
AND TARIFAS.ID_TIPO_ACTIVIDAD = TIPO_ACTIVIDAD.ID
AND TIPO_ACTIVIDAD.ID_ACTIVIDAD = ACTIVIDAD.ID");
oci_execute($stallTableCarrito);
$array=array(
0=>array(),
1=>array(),
2=>array(),
3=>array(),
4=>array()
);
while (($row=oci_fetch_array($stallTableCarrito,OCI_BOTH))!=false){
array_push($array[0],$row['NOM_ACTIVIDAD']);
array_push($array[1],$row['NOM_TACTIVIDAD']);
array_push($array[2],$row['TIPO']);
array_push($array[3],$row['TEMPS_KM']);
array_push($array[4],$row['PRECIO']);
}
for ($x=0;$x<count($array[0]);$x++){
echo "<tr>";
echo " <td>".$array[0][$x]."</td>";
echo " <td>".$array[1][$x]."</td>";
echo " <td>".$array[2][$x]."</td>";
echo " <td>".$array[3][$x]."</td>";
echo " <td>".$array[4][$x]."</td>";
echo " <td><input type='submit' class='carritoElim' value=''></td>";
echo "</tr>";
}
}
echo "</table>";
echo "</div>";
Basically that's a shopping form.
And where is the problem? When i send the pushed checkboxes with the button class='carrito', the form by default refresh the page and clears my array, what can i do?
In your first part of code, is your form tag open ? (I guess it is if this one works)
In the second part, is your <input type='submit' class='carritoElim' value=''> tag in a form ?
Because if it's not, you gonna have a bad time ;-)
Maybe in the last form you should generate hidden input with same names as your first form and same values.
If you don't I guess your variable $idTActi won't be set anymore and it won't succeed the first test if(isset($idTActi)). That could be why you get a cleared page.
If you have a multi step form in the same php page, for this kind of html code :
<form method=POST url="myURL">
<select name="select1">[...]</select>
<select name="select2">[...]</select>
<!-- VARIOUS PART : may not be displayed -->
<div id="checkboxes">
<input type="hidden" name="boxStep" value="1"/>
<input type="checkbox" name="cb1" value="1"/>
[...]
</div>
<!-- END OF VARIOUS PART -->
</form>
Then you need php tests in this order :
// if post request
if (isset($_POST)) {
if (isset($_POST['boxStep'])) {
// behavior when checkboxes values are sent
} else {
if (isset($_POST['select2'])) {
// behavior when second select is filled
// display "VARIOUS PART"
} else {
// behavior when only first select is filled
// Do not display "VARIOUS PART"
}
}
} else {
// default behavior (no select filled)
// Do not display "VARIOUS PART"
}
Apolo

How to create submit form in a row and relate input to that row?

Hey Guys, I have a question for you.
Imagine that I wanted to be able to keep track of how many miles I've ran every week, so that I could
compare it to the goals I've set for each week. So i've created this table by the use of mysql_fetch_row.
$result=mysql_query("SELECT * FROM randomtable ORDER BY week ASC");
echo "<Table id='result' cellspacing='0'>
<tr class='toprow'>
<th>Week</th>
<th>Goal</th>
<th>Actual Number of Miles</th>
</tr>";
while($row = mysql_fetch_row($result))
{
echo "<tr class='standardrow'>";
echo "<td>$row[0]</td>";
echo "<td>$row[1]</td>";
echo "<td><form><input method='post' type='number'></form></td>";
echo "</tr>";
}
echo "</table>";
This piece of code resultet in a table with 10 weeks with 10 goals - and a column for the actual number of miles. This column should include 10 input forms where the actual number of miles can be submitted. But how do I relate the input from the submit form to the row in which the submit form is positioned?
The primary key is the week - so this would be the one to relate to.
Hope you understand what my problem is:)
To do this you would use a hidden input field.
When you echo each row, and the form in that row, you would simply add an extra line:
`<input type="hidden" name="row_id" value="' . $row['id_column'] . '" />';
In full, your code would be:
$result=mysql_query("SELECT * FROM randomtable ORDER BY week ASC");
echo "<Table id='result' cellspacing='0'>
<tr class='toprow'>
<th>Week</th>
<th>Goal</th>
<th>Actual Number of Miles</th>
</tr>";
while($row = mysql_fetch_row($result))
{
echo "<tr class='standardrow'>";
echo "<td>$row[0]</td>";
echo "<td>$row[1]</td>";
echo "<td>
<form>
<input method='post' type='number'>
<input type='hidden' name='row_id' value='" . $row['id_column'] . "' />
</form>
</td>";
echo "</tr>";
}
echo "</table>";
I think there should be some modifications that has to be done in loop.
echo "<td><form method='post'><input type='number' value='".$rows['col_name']."'><input type='submit' ></form></td>";
This code adds a submit button to each row. But, this shouldn't be what I think.
It should be rather this way,
echo "<form method='post'> ";
while($row = mysql_fetch_row($result))
{
echo "<tr class='standardrow'>";
echo "<td>$row[0]</td>";
echo "<td>$row[1]</td>";
echo "<td><input type='number' value='".$rows['col_name']."'></td>";
echo "</tr>";
}
echo "<input type='submit' ></form>";
Or make the input field look like this.
'<input type="text" name="row['.$row['id_column'].'][miles]" />';
It will return you an array when you post it.
foreach($_POST['row'] as $key => $value){
// $key is your primary key
// $value['miles'] is your input value
}

How to access all the <form> elements that have been dynamically generated by PHP-MySQL in $_GET upon submitting the form?

I have a simple DB and a small table in it. This table named STOCK has only one column - names of different items in a stationery.
I am dynamically generating a form in PHP-MySQL which fetches Item from STOCK (such as Pencil, Pen etc.) and displays them by using echo() function. So I have generated a form which displays Item and correspondingly an <input> text box. Upon submitting this form, how can I access all the Names and their text inputs by traversing through the $_GET array?
The dynamically generated form is:
$res = mysql_query("SELECT * FROM Stock");
echo "<form name='input' action='add_stock_later.php' method='get'>";
echo "<table align='left' border='1'>
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Remarks</>
</tr>";
while($row = mysql_fetch_array($res))
{
$item = $row['Item'];
echo "<tr>";
echo "<td>" . $item . "</td>";
echo "<td><input type='text' name='$item'></td>";
echo "<td><input type='text' name='Remarks'></td>";
echo "</tr>";
}
echo "<tr><td></td>
<td align='middle'><input type='submit' value='Submit'></td></tr>";
echo "</table>";
Now in the add_stock_later.php, how can I access all these $item and it's corresponding input without having to manually do it using $_GET['Pencil'], $_GET['Pen'] and so on.
First edit your form.
echo "<td><input type='text' name='".$item."[quantity]'></td>";
echo "<td><input type='text' name='".$item."[remarks]'></td>";
Then use foreach().
foreach ($_GET as $stationery => $info) {
$stationery; // name of the stationery
$info["quantity"]; // quantity of the stationery
$info["remarks"]; // remarks for the stationery
}
Something like so, add to it of course.
$required = array('pencil', 'pen', 'paper', 'staples');
foreach ($required as $getKey){
if (isset($_GET[$getKey]) && $_GET[$getKey] !=''){
$$getKey = trim($_GET[$getKey]);
}
}
This turns $_GET['pencil'] into $pencil and you don't need to worry about knuckleheads trying to inject garbage.

Categories