Submit Button with multiple ID Inside Looping?(Shopping Cart) - php

I want to Create a Shoping Cart on PHp,
The Code is simple, When the customer fill the QTY and click button Add to cart, the code will save the PRoduct ID and Qty to a Cart Table. But the problem is that Form inside the Looping. And How Can I Get ID and Qty only from The button that Customer Click.
The Program look like this
And The Script Like This
<?php
if(isset($_POST[ADD]))
{
$qty = $_POST[QTY];
$harga = $_POST[HARGA_ASLI];
$id = $_POST[ID];
print_r($_POST);
}
$kolom = 3;
$sql = "SELECT *,FORMAT(harga,0)AS harga_digit FROM item";
$hasil = mysql_query($sql);
echo "<form method=POST action=index.php>";
echo "<table>
<tr>";
$i = 0;
while($data=mysql_fetch_array($hasil))
{
if($i >= $kolom)
{
echo "</tr><tr>";
$i = 0;
}
$i++;
echo "<td align='center'><br><a href='detailBarang.php?ID=$data[ID]'><img src='$data[img]' width='200' height='150'/><br>$data[nama_produk]</a><br>
Rp. $data[harga_digit]<br>
<input type='submit' name='ADD' id='ADD' value='Add to Cart'>
<input type='text' name='QTY' id='QTY' placeholder='Qty' /><br>
<input type='hidden' name='HARGA_ASLI' id='HARGA_ASLI' value='$data[harga]' /><br>
<input type='hidden' name='ID' id='ID' value='$data[ID]' />
<br></td>";
}//end of while
echo "<tr></table>";
echo "</form>";
?>
If i fill the Qty and click Add to Cart, only the last Item can Post The Data.
How To Post The data Only for Customer Choose?
Im very Appreciated Your Answer.
Thanks

First, let's convert your MySQL to MySQLi. More explanation inside the comments /* */:
<?php
$connection=mysqli_connect("YourHost","YourUsername","YourPassword","NameofYourDatabase");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
$res=mysqli_query($con,"SELECT * FROM item");
while($row=mysqli_fetch_array($res)){
$nameofsubmitbutton=$row['ID'];
if(isset($_POST[$nameofsubmitbutton])){
$nameofproduct=$row['namaproduk'];
$nameofnumbersubmitted=$nameofsubmitbutton."number";
$quantity=$_POST[$nameofnumbersubmitted];
if(empty($quantity)){
echo "You wanted to buy a ".$nameofproduct."?<br>Type in a number so you can add it to your cart.";
}
else {
mysqli_query($connection,"INSERT INTO yourTable ('','') VALUES ('$quantity','$nameofproduct')");
echo "You bought ".$quantity." of ".$nameofproduct;
}
} /* END OF IF ISSET */
} /* END OF WHILE LOOP $RES */
$kolom = 3;
$hasil = mysqli_query($connection,"SELECT *,FORMAT(harga,0) AS harga_digit FROM item"); /* YOU SURE WITH THIS QUERY? */
echo "<form method=POST action=''>"; /* SUBMIT ON ITSELF */
echo "<table><tr>";
$i = 0; /* THIS WOULD ALSO SET AS YOUR COUNTER */
while($data=mysqli_fetch_array($hasil))
{
$id=$data['ID'];
if($i >= $kolom){
echo "</tr><tr>";
$i = 0;
} /* END OF IF $i >= $KOLOM */
$i++;
echo "<td align='center'><br><a href='detailBarang.php?ID=$data[ID]'><img src='$data[img]' width='200' height='150'/><br>".$data[nama_produk]."</a><br>Rp. ".$data[harga_digit]."<br>"; /* IF TO ECHO VARIABLES, USE ".$variable." */
$numbername=$id."number";
echo "<input type='number' name='$numbername' id='QTY' placeholder='Qty' /><br>"; /* CHANGE YOUR INPUT TYPE TO NUMBER */
/* NO NEED FOR THE HIDDEN INPUT */
echo "<input type='submit' name='$id' id='ADD' value='Add to Cart'></td>"; /* CHANGE THE NAME OF SUBMIT BUTTON TO THE CORRESPONDING ID FROM YOUR TABLE */
} /* END OF WHILE LOOP */
echo "<tr></table>";
echo "</form>";
?>
I tried it on my local computer. You should too.
Here's a sample screen shot.

This may do the trick:
<?php
$kolom = 3;
$sql = "SELECT *,FORMAT(harga,0)AS harga_digit FROM item";
$hasil = mysql_query($sql);
while($data=mysql_fetch_array($hasil))
{
if(isset($_POST['ADD'.$data[ID]]))
{
$qty = $_POST['QTY'.$data[ID]];
$harga = $_POST['HARGA_ASLI'.$data[ID]];
$id = $_POST['ID'.$data[ID]];
print_r($_POST);
}
}
echo "<form method=POST action=index.php>";
echo "<table>
<tr>";
$i = 0;
while($data=mysql_fetch_array($hasil))
{
if($i >= $kolom)
{
echo "</tr><tr>";
$i = 0;
}
$i++;
echo "<td align='center'><br><a href='detailBarang.php?ID=$data[ID]'><img src='$data[img]' width='200' height='150'/><br>$data[nama_produk]</a><br>
Rp. $data[harga_digit]<br>
<input type='submit' name='ADD'".$data[ID]." id='ADD' value='Add to Cart'>
<input type='text' name='QTY'".$data[ID]." id='QTY' placeholder='Qty' /><br>
<input type='hidden' name='HARGA_ASLI'".$data[ID]." id='HARGA_ASLI' value='$data[harga]' /><br>
<input type='hidden' name='ID' id='ID'".$data[ID]." value='$data[ID]' />
<br></td>";
}//end of while
echo "<tr></table>";
echo "</form>";
?>

Related

PHP dynamic table

I have to make a dynamic table n*n , the user first gives the number n and the program makes a 5*5 table with check box this part I have make it, the second part is the user checks same of the checkbox and clicks on submit and the program makes again a table 5*5 but in the place of check box which checks is colored. I have uploaded and image.
Sorry for my bad English, thanks for your time.
enter image description here
<form name="form" action="" method="get">
<input type="text" name="subject" id="subject" value="Give value">
</form>
<?php
$rows = $cols = $name = "";
if(isset($_GET['subject']))
$rows = $cols = $_GET['subject'];
if(isset($_POST['check_list']))
$name = $_POST['check_list'];
if(isset($_GET['subject'])){
echo "<form action='my.php' method='post'>";
echo "<table border='1'>";
for($tr=1;$tr<=$rows;$tr++){
echo "<tr>";
for($td=1;$td<=$cols;$td++){
echo "<td><input type='checkbox' name='check_list[]' value='value ".$td."'></td>";
}
echo "<tr>";
}
echo "</table>";
echo "<input type='submit' />
</form>";
}
// this part of code is not make the third excecution the number 3 image
echo $cols;
echo "<table border='1'>";
for($tr=1;$tr<=$rows;$tr++){
echo "<tr>";
foreach($_POST['check_list'] as $value){
if($tr == $value[td])echo "<td bgcolor='#FF0000'></td>";
else
echo "<td> </td>";
}
echo "</tr>";
}
echo "</table>";
?>

Check a checkbox when element exists in the database

I have a table that has different names of competences and another one in which we have the competence_ID and the user_ID that has that competence. I have a form in which I submit the competences that apply to a certain user. Now, I want to retrieve these competences and check boxes in case they are valid.
I use this code, but it does not seem to work.
<?php
include "db.php";
$employees=mysql_query("SELECT * FROM asiakas");
echo "<form method='post' action='' id='employeesselection'><select name='select_employee' id='select_employee'>";
while($row=mysql_fetch_array($employees)){
$selected = ($row['Id'] == $_POST['select_employee'])?'selected="selected"':'';
echo '<option '.$selected.' value="'.$row['Id'].'">'.$row['Etunimi'].' - '. $row['Sukunimi'].'</option>';
}
echo "</select><input type='hidden' name='action' value='selectedemployee'>
<input type='submit' value ='submit' name='submit'><br/>";
if(isset($_POST['select_employee'])){
$specific=mysql_query("SELECT Id, Sukunimi,Etunimi from asiakas WHERE Id=".$_POST['select_employee']);
$sp=mysql_fetch_array($specific);
}
if(isset($sp['Etunimi']) && isset($sp['Sukunimi'])){
$comp=mysql_query("SELECT * FROM Competences");
echo "<br/>select competences for: ". $sp['Etunimi'];
$id= $sp['Id'];
$result=mysql_query("SELECT distinct c_ID from User_Competence WHERE e_ID=".$id);
while($test=mysql_fetch_array($result))
{
echo $test['c_ID'];
}
echo "<table><th>valid?</th><th>Competence description</th>";
$counter=0;
$traverse=0;
while($compi=mysql_fetch_array($comp)){
$checked='';
if($test[$traverse]==$counter){
$checked="checked";
$traverse++;
}
$counter ++;
echo "<tr><td><input type='checkbox'" .$checked." name='c[]' value='".$compi['Competence_ID']."'></td><td>".$compi['Competence_Description']."</td></tr>";
}
echo "</table>";
echo "<input type='hidden' name='action' value='selectchecked'>";
echo "<input type='submit' value='submit checks'>";
}
if(isset($_POST) && !empty($_POST)){
print_r($_POST);
}
if(isset($_POST['action']) && $_POST['action']='selectchecked'){
if (isset($_POST['c'])){
$s = $_POST['c'];
foreach ($s as $k => $v) {
if (is_array($v)) {
// array_push($s, implode('', array($v [$what])));
}
};
echo $abc= implode(',', $s);
for ( $a=0;$a<count($s);$a++){
$ar=explode(',',$abc);
echo $var= $ar[$a];
$q=mysql_query("INSERT INTO user_competence(c_ID, e_ID) VALUES ('".$var."','".$id."')");
}
}
}
echo "</form>";
?>
If you put checked as an attribute on the <input type="checkbox"> it will be checked, even if you leave the actual value of the attribute empty.
So change the following parts from...
$checked="checked";
...
echo "<tr><td><input type='checkbox' checked='".$checked."' name='c[]' ...
Into...
$checked="checked='checked'";
...
echo "<tr><td><input type='checkbox' ".$checked." name='c[]' ...
Which will mean if the $test[$traverse$] is true, checked='checked' will be placed into the HTML, otherwise it will be left out.

online quiz using php and mysql(radio button)

please help, i'm developing an online quiz application. All the questions and answers will be selected from the database. Where i'm having probkem with is to get the values from the radio button whether checked or not. bellow is the code that generate the questions and answers from database.
if (!isset($_POST['submit'])) {
echo "<form method=post action='#'>";
echo "<table border=0>";
while ($row = mysql_fetch_array($display)) {
$id = $row["id"];
$question = $row["question"];
$opt1 = $row["ans1"];
$opt2 = $row["ans2"];
$opt3 = $row["ans3"];
$opt4 = $row["ans4"];
$opt5 = $row["ans5"];
$answer = $row["ans"];
echo "<tr><td colspan=3><br><b>$question</b></td></tr>";
echo "<tr><td>$opt1 <input type=radio name=q$id value=\"$opt1\"></td><td>$opt2 <input type=radio name=q$id value=\"$opt2\"></td><td>$opt3 <input type=radio name=q$id value=\"$opt3\"></td><td>$opt4 <input type=radio name=q$id value=\"$opt4\"></td><td>$opt5 <input type=radio name=q$id value=\"$opt5\">q$id</td></tr>";
}
echo "</table>";
echo "<input type='submit' value='See how you did' name='submit'>";
echo "</form>";
}
the name of the radio button is
<input type='radio' name='q$id' value='$opt4' />
How do i get the value of the checked radio button?
or is my PHP code wrong?
what i needed is to output what is selected if a radio button is checked.
if(isset($_POST['submit']))
{
$value = $_POST[''];//the value of the radio button, i don't know what to put here
$n = count($value);
for($i=0; $i < $n; $i++)
{
echo $value[$i];
}
}
Try:
if(isset($_POST['submit']))
{
$value = $_POST;//the value of the radio button, i don't know what to put here
$n = count($value);
for($i=0; $i < $n; $i++)
{
echo $value[$i];
}
}
$_POST[''] was wrong. You needed to use just $_POST.
You could also just use foreach here:
if(isset($_POST['submit']))
{
$values = $_POST;//the value of the radio button, i don't know what to put here
foreach($values as $value)
{
echo $value;
}
}
$_POST is just a array containing whatever your form submited. If you had a name textfield you would use:
echo $_POST['name'];
to echo it.
Try
var_dump("<PRE>", $_POST);
And you will see exactly how your form is being organised. Link to documentation
thanks for your response. i was able to come out with this code and it works but i don't know if the structure or the way i solved it is proper or good enough.
<?php
if (!isset($_POST['submit'])) {
echo "<form method=post action='#'>";
echo "<table border=0>";
while ($row = mysql_fetch_array($display)) {
$id = $row["id"];
$question = $row["question"];
$opt1 = $row["ans1"];
$opt2 = $row["ans2"];
$opt3 = $row["ans3"];
$opt4 = $row["ans4"];
$opt5 = $row["ans5"];
$answer = $row["ans"];
echo "<tr><td colspan=3><br><b>$question</b></td></tr>";
echo "<tr><td><input type=radio name=$id value=\"$id $opt1\">$opt1 </td><td><input type=radio name=$id value=\"$id $opt2\">$opt2 </td><td><input type=radio name=$id value=\"$id $opt3\">$opt3 </td><td><input type=radio name=$id value=\"$id $opt4\">$opt4 </td><td><input type=radio name=$id value=\"$id $opt5\">$opt5 <br>";
}
echo "</table>";
echo "<input type='submit' value='See how you did' name='submit'>";
echo "</form>";
}
?>
what i did was to include the id of the question in the value of the radio button
<input type=radio name=$id value=\"$id $opt1\">
i collect the values of the radio button using $_POST as suggested, i then explode the value into two arrays so the first array will contain the question id and the second will contain the actual value of the radio button (answer).
<?php
elseif (isset($_POST['submit']))
{
var_dump("<PRE>", $_POST);
$sd = $_POST;
foreach($sd as $sd)
{
$tok = explode(" ", $sd, 2);
$w = mysql_query("select * from `questions` WHERE `id` = '$tok[0]'")or die(mysql_error());
if(mysql_num_rows($w) == 1)
{
$sf = mysql_fetch_object($w);
echo $tok[1].".......".$sf->ans."<br>";
}
}
}
?>
it works perfectly but will it give efficient result?

Restore radio button selection when revisiting a page

I have a PHP script that allows users to enter grades by selecting a radio button that corresponds to the students grade. It allows them to view the selected grades before they can be finally submitted. I also want the page to have the ability to go back to the selection page and remember the radio buttons that were selected so that the user doesn't have to set all of them again when going back. Here is what I have coded so far, it takes the user back to selection page but doesn't restore the radio button selection.
<?php
session_start();
$script_name = $_SERVER["PHP_SELF"];
if(!isset($_SESSION["course"]) || !isset($_SESSION["course"])) {
$_SESSION["course"] = $_POST["coursename"];
$_SESSION["section"] = $_POST["section"];
}
if(($_SESSION["authenticated"] == true || isset($_POST["back"])) && !isset($_POST["continue"])) {
$course = $_SESSION["course"];
$section = $_SESSION["section"];
$file_name = $course.$section.".txt";
$_SESSION["filename"] = $file_name;
// Open file containing student names.
$fp = fopen($_SESSION["filename"], "r") or die("Could not open file");
$students = array();
$i = 0;
echo "<h2>Grades Submission Form</h2>";
echo "<h2>Course: $course, Section: $section</h2>";
echo "<form action=\"$script_name\" method='post'>";
echo "<table border='1'>";
while (!feof($fp)) {
$line = trim(fgets($fp));
$students[$i++] = $line;
echo "<tr><td>$line</td>";
echo "<td><input type='radio' name=\"$line\" value='A'/>A</td>";
echo "<td><input type='radio' name=\"$line\" value='B'/>B</td>";
echo "<td><input type='radio' name=\"$line\" value='C'/>C</td>";
echo "<td><input type='radio' name=\"$line\" value='D'/>D</td>";
echo "<td><input type='radio' name=\"$line\" value='F'/>F</td>";
echo "</tr>";
}
echo "</table><br>";
echo "<input type='submit' name='continue'/>";
echo "</form>";
} elseif($_SESSION["authenticated"] == true && isset($_POST["continue"]) && !isset($_POST["back"])) {
unset($_POST["continue"]);
$keys = array_keys($_POST);
$values = array_values($_POST);
echo "<h2>Grades to Submit</h2>";
echo "<table border='1'>";
echo "<tr><th>Name</th><th>Grade</th></tr>";
for($i = 0; $i < count($keys); $i++) {
echo "<tr><td>{$keys[$i]}</td><td>{$values[$i]}</td></tr>";
}
echo "</table><br>";
echo "<form action='confirmation.php' method='post'>";
echo "<input type='submit' value='Submit Grades'/>";
echo "</form>";
echo "<form action=\"$script_name\" method='post'>";
echo "<input type='submit' value='Back'/>";
echo "</form>";
} else {
header("Location: main.php");
}
?>
You could serialize() an array containing the radio button states and store it in your session. When you go back, all you have to do is unserialize it and set the data again.

html table to display php photo gallery

I need to display a photo gallery in a table, I want five pictures on each line, but can't find the way to insert </tr><tr> after each fifth picture.
Here's my code:
<?php
// table name
$tbl_name=gallery1;
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
while($rows= mysql_fetch_assoc($result)){
$id = $rows['id'];
$path = $rows['path'];
$image_name = $rows['image_name'];
$title = $rows['title'];
?>
<img src="<?php echo $path."/".$image_name;?>" height="120"/>Name:<?php echo $title;?>
<?php
echo "<form action='pictry.php' enctype='multipart/form-data' method='post'>
<input name='file[]' type='hidden' value='".$image_name."' />
<input name='id' type='hidden' id='id' value='".$id."'/>
<input type='submit' name='button' id='button' value='Delete Picture' /></form>";
}
?>
Replace the line
while($rows= mysql_fetch_assoc($result)){
with
for($i = 0; $rows= mysql_fetch_assoc($result); ++$i) {
Then you place something like this into the for loop.
if($i % 5 == 0) { /* insert stuff */ }
Untested Code
<?php
$perrow = 5;
$i = 0;
echo '<table>';
echo '<tr>';
while($rows = mysql_fetch_assoc($result)) {
echo '<td><img src=[grapresultfromrows] /></td>';
++$i;
if($i == $perrow) {
$i = 0;
echo '</tr>';
echo '<tr>';
}
}
// If not a multiple of $perrow you need to add extra cells
for($i; $i < $perrow; ++$i) {
echo '<td></td>';
}
echo '</tr>';
echo '</table>';
?>

Categories