Iterate over database table values - php

I have a problem with trying to iterate over the amount of results returned in a query,I have a database table called Cart with the following fields:
ItemCode //Unique Code of Item
ItemDesc //Description / Name ofItem
ItemUnitPrice //Unit Price for Item
ItemCategory //Category of Item e.g. Books, CD, DVD etc...
Quantity //Quantity of Item(s) in cart
I want to loop over all the records displayed in my display.php (which simply prints all the data in the Cart table) and then multiply the ItemUnitPrice by the Quantity for every item and store it in a variable to store the total price for everything contained in display.php.
I want something like this:
LOOP
$Total= $ItemUnitPrice * $Quantity;
END LOOP
I am using MySQL and I'm not too sure how I should loop to get the total for each and every item.
So in a nutshell I want to find the total (ItemUnitPrice * Quantity) for each and every item in the database table and store it in a variable.
EDIT:
$query="SELECT * FROM Cart";
$result=mysql_query($query);
$num=mysql_num_rows($result);
$cartTotalPrice = 0;
while($row = mysql_fetch_assoc($result))
{
$cartTotalPrice += ($row['itemUnitPrice']*$row['Quantity']);
}
$_SESSION['totalCost'] = $cartTotalPrice;
mysql_close();
session_start();
echo "<b><center> Islamic Book Store - Your Shopping Cart </b><br/><br/>";
$i=0;
echo "<table border=1><tr><th>Item Code</th><th>Item Desc,</th>";
echo "<th> Item Unit Price</th><th>Item Category</th><th>Quantity</th><th>Image</th> <th>Update Quantity</th></tr>";
while ($i < $num)
{
$ItemCode = mysql_result($result,$i,"ItemCode");
$ItemDesc = mysql_result($result,$i,"ItemDesc");
$ItemUnitPrice = mysql_result($result,$i,"ItemUnitPrice");
$ItemCategory = mysql_result($result,$i,"ItemCategory");
$Quantity = mysql_result($result,$i,"Quantity");
echo "<tr><td align=center>$ItemCode</td><td align=center>$ItemDesc</td>";
echo "<td align=center>£$ItemUnitPrice</td>";
echo "<td align=center>$ItemCategory</td><td align=center>$Quantity</td>";
$i++;
}
echo "</table><center>";
echo "$num Item(s) found.";
echo "<br/><br/><center><form action = 'clear.php'><input type='submit' value='Clear'> </form></center>";
?>
<html>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_BLANK">
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="business" value="email#example.com" />
<input type="hidden" name="item_name" value="<? echo $ItemDesc ?>" />
<input type="hidden" name="item_number" value="TEST ITEM NUMBER" />
<input type="hidden" name="amount" value="<? echo $cartTotalPrice ?>" />
<input type="hidden" name="currency_code" value="GBP" />
<input type="hidden" name="lc" value="GB" />
<input type="hidden" name="bn" value="PP-BuyNowBF" />
<input src="paypal/purchase.png" name="Submit" type="image" value="purchase" alt="Purchase" />
</form>
</html>

First of all, get out of the habit of using mysql_* functions! Use PDO or mysqli.
Why shouldn't I use mysql_* functions in PHP?
http://php.net/pdo
Secondly, I'm sad to tell you, your code is completely wrong!
session_start();
$query = "SELECT * FROM Cart";
$result = mysql_query($query);
$num = mysql_num_rows($result);
$cartTotalPrice = 0;
while($row = mysql_fetch_assoc($result))
{
$cartTotalPrice += ($row['itemUnitPrice']*$row['Quantity']);
echo "<tr><td align=center>{$row['itemCode']}</td><td align=center>{$row['ItemDesc']}</td>";
echo "<td align=center>{$row['ItemUnitPrice']}</td>";
echo "<td align=center>{$row['$ItemCategory']}</td><td align=center>{$row['$Quantity']}</td></tr>";
}
$_SESSION['totalCost'] = $cartTotalPrice;
// $_SESSION['totalCost'] is now available on every page (as long as you use start_session() before any output)
mysql_close();

Try the below code I hope it works, I made the corrections and mentioned them in comments:
$query="SELECT * FROM Cart";
$result=mysql_query($query);
$num=mysql_num_rows($result);
$cartTotalPrice = 0;
while($row = mysql_fetch_assoc($result))
{
$cartTotalPrice += ($row['itemUnitPrice']*$row['Quantity']);
}
session_start();
$_SESSION['totalCost'] = $cartTotalPrice;
// mysql_close(); // here you are closing your mysql connection before using mysql_result refer to the example in http://php.net/manual/en/function.mysql-result.php
// session_start(); // session start should go above you dont need session if the whole script is in the same page. no need to save the variable to session
echo "<b><center> Islamic Book Store - Your Shopping Cart </b><br/><br/>";
$i=0;
echo "<table border=1><tr><th>Item Code</th><th>Item Desc,</th>";
echo "<th> Item Unit Price</th><th>Item Category</th><th>Quantity</th><th>Image</th> <th>Update Quantity</th></tr>";
while ($i < $num)
{
$ItemCode = mysql_result($result,$i,"ItemCode");
$ItemDesc = mysql_result($result,$i,"ItemDesc");
$ItemUnitPrice = mysql_result($result,$i,"ItemUnitPrice");
$ItemCategory = mysql_result($result,$i,"ItemCategory");
$Quantity = mysql_result($result,$i,"Quantity");
echo "<tr><td align=center>$ItemCode</td><td align=center>$ItemDesc</td>";
echo "<td align=center>£$ItemUnitPrice</td>";
echo "<td align=center>$ItemCategory</td><td align=center>$Quantity</td>";
$i++;
}
echo "</table><center>";
echo "$num Item(s) found.";
echo "<br/><br/><center><form action = 'clear.php'><input type='submit' value='Clear'> </form></center>";
mysql_close();
?>
<html>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_BLANK">
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="business" value="info#asianweddingservices.org" />
<input type="hidden" name="item_name" value="<? echo $ItemDesc ?>" />
<input type="hidden" name="item_number" value="TEST ITEM NUMBER" />
<input type="hidden" name="amount" value="<? echo $cartTotalPrice ?>" />
<input type="hidden" name="currency_code" value="GBP" />
<input type="hidden" name="lc" value="GB" />
<input type="hidden" name="bn" value="PP-BuyNowBF" />
<input src="paypal/purchase.png" name="Submit" type="image" value="purchase" alt="Purchase" />
</form>
</html>

Related

Something wrong while deleting data from DB

I'm trying to delete some information from the database, but when I ask the user to confirm action, something goes wrong. Can you help me?
The script prints the categories to choose if nothing is settled. Then, It asks the user to delete or not delete the categories chosen. In the end, it deletes what was chosen.
But there's some error in the last part(first in the script) and I cannot understad where it's going wrong:
<?php
//If the user confirm to delete...
if(isset($_POST['eliminazione_conferma']) and $_POST['eliminazione_conferma']=='conferma'){
//if conferma_eliminazione=1, don't delete
if(isset($_POST['conferma_eliminazione']) and $_POST['conferma_eliminazione']=='1'){
echo 'Eliminazione annullata';
}else{//Delete if conferma_eliminazione=0
while($row=$categoria){
$delete= "DELETE FROM categorie WHERE $row = category_id";
$query=mysql_query($delete);
echo "$row eliminato\n";
}
}
}else{//ELSE, print the form to confirm action
if(isset($_POST['eliminazione']) and $_POST['eliminazione']=='delete'){
//Array with the chosen "categories"
$categoria=isset($_POST['categoria']) ? $_POST['categoria'] : array();
//Print the chosen categories to ask confirmation
echo'Sicuro di voler eliminare le seguenti categoire?<br />';
foreach($categoria as $row){
echo "$row<br />\n";
}
//Yes = 0, No = 1
echo '<form method="post" action="',$_SERVER['REQUEST_URI'],'">
<input type="radio" name="conferma_elimiazione" value="0" />Si<br />
<input type="radio" name="conferma_eliminzione" value="1" />No<br />
<input type="hidden" name="eliminazione_conferma" value="conferma" />';
foreach($categoria as $row){
echo'<input type="hidden" name="categoria[]" value="',$row,'" />',"\n",'' ;
}
echo'
<input type="submit" value="Conferma" />
</form>';
}else{//In the end, if nothing is settled, print the form to check the category to delete
//Select the categories from the database
echo'<form method="post" action="',$_SERVER['REQUEST_URI'],'" />',"\n",'';
$select = "SELECT nome,category_id FROM categorie ORDER BY category_id" ;
$select_result=mysql_query($select) or die("Mysql Error: ".mysql_error());
while($row = mysql_fetch_assoc($select_result)){
echo '<input type="checkbox" name="categoria[]" value="',$row['category_id'],'">',$row['nome'],'<br />';
}
echo'<input type="hidden" name="eliminazione" value="delete" />
<input type="submit" name="submit" value="Elimina" />
</form>';
}
}
The problem with the query
$delete= "DELETE FROM categorie WHERE $row = category_id";
is
here
WHERE $row = category_id";
What is category_id?
Do you have a value for that?
Probably you want WHERE category_id=/*something here like $row['column_name']*/
Thanks everyone for the help, but I've solved my problem in this way(the script wasn't transformig the value of "conferma_eliminazione" in the integer type):
<h2>Modifica o Elimina Categoria </h2>
<?php
if(isset($_POST['eliminazione_conferma']) and $_POST['eliminazione_conferma']=='conferma'){
$categoria=isset($_POST['categoria']) ? $_POST['categoria'] : array();
$a=(int)$_POST['eliminazione'];
if($a=='1'){
echo 'Eliminazione annullata';
echo "\n";
}elseif($a=='0'){
foreach($categoria as $row){
$delete= "DELETE FROM categorie WHERE $row = category_id";
$query=mysql_query($delete);
echo "$row eliminato\n";
}
}
}else{
if(isset($_POST['eliminazione']) and $_POST['eliminazione']=='delete'){
$categoria=isset($_POST['categoria']) ? $_POST['categoria'] : array();
echo'Sicuro di voler eliminare le seguenti categoire?<br />';
foreach($categoria as $row){
echo '',$row,'<br />',"\n";
}
echo '<form method="post" name="form_eliminazione_categoria" action="',$_SERVER['REQUEST_URI'],'">',"\n",'
<input type="radio" name="eliminazione" value="0" />Si<br />' ,"\n",'
<input type="radio" name="eliminazione" value="1" />No<br />',"\n",'
<input type="hidden" name="eliminazione_conferma" value="conferma" />',"\n",'';
foreach($categoria as $row){
echo '<input type="hidden" name="categoria[]" value="',$row,'" /><br />',"\n",'';
}
echo'
<input type="submit" value="Conferma" />
</form>';
}else{
echo'<form method="post" action="',$_SERVER['REQUEST_URI'],'" />',"\n",'';
$select = "SELECT nome,category_id FROM categorie ORDER BY category_id" ;
$select_result=mysql_query($select) or die("Mysql Error: ".mysql_error());
while($row = mysql_fetch_assoc($select_result)){
echo '<input type="checkbox" name="categoria[]" value="',$row['category_id'],'">',$row['nome'],'<br />';
echo "\n";
}
echo'<input type="hidden" name="eliminazione" value="delete" />',"\n",'
<input type="submit" name="submit" value="Elimina" />',"\n",'
</form>';
}
}

radio button in while loop

i am coding a page for the attendance of students and in the page all the students name are retrieved dynamically from database using while loop and inside the while loop i have used a radio button.
my problem is the radio button work's correctly but i am unable to insert the value of radio buttons into database.here is my code :
include'connection.php';
#$id = mysql_real_escape_string($_GET['id']);
$res=mysql_query("SELECT * FROM `std_register` AS p1 ,`sims-register-course` AS p2 WHERE p2.semester=p1.std_semester and p2.department=p1.std_department and p2.id = '".$id."'");
if ($res==FALSE) {
echo die(mysql_error());
}
while ($row=mysql_fetch_assoc($res)) { ?>
<input type="hidden" id="dept_0" name="dept[]" value="<?php echo $row["department"] ?>">
<input type="hidden" id="course_name_1" name="course_name[]" value="<?php echo $row["course_name"] ?>">
<input type="hidden" id="std_semester_2" name="std_semester[]" value="<?php echo $row["semester"] ?>">
<input type="hidden" id="std_id_3" name="std_id[]" value="<?php echo $row["id"] ?>">
<input type="hidden" id="std_name_4" name="std_name[]" value="<?php echo $row["std_name"] ?>">
<tr>
<td class =info><?php echo $row["std_name"];?></td>
<td><input type="radio" name="<?php echo "status['".$row["std_name"]."']" ?>" value="1"></td>
<td><input type="radio" name="<?php echo "status['".$row["std_name"]."']" ?>" value="2"></td>
</tr>
<?php }?>
</table><br>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-3">
<input type="submit" name="submit" value="Assign" class="btn btn-large btn-block btn-primary"></div></div>
</form>
<?php
for ($i=0; $i < 4; $i++) {
if(isset($_POST["submit"])) {
$stdid = mysql_real_escape_string($_POST['std_id'][$i]);
$dptname = mysql_real_escape_string($_POST['dept'][$i]);
$courseName = mysql_real_escape_string($_POST['course_name'][$i]);
$stdSemester = mysql_real_escape_string($_POST['std_semester'][$i]);
$std_name = mysql_real_escape_string($_POST['std_name'][$i]);
$present = mysql_real_escape_string($_POST['status'][$i]);
$totalClasses = $present;
$insrt = mysql_query("INSERT INTO `attendence_student` (department_name,courseName,semester,present,absent,total_classes) VALUES('$dptname','$courseName','$stdSemester','$present',0,0)") or die(mysql_error());
}
}
and is it possible to insert values from this radio buttons to two columns of database?
I am not sure but try to add 'checked' property in radio input
<input type="radio" name="<?php echo "status[".$row["std_name"]."]" ?>" value="1" checked></td>
Or
use Select tag instead of radio button
EDIT
use this code to insert in present column or absent column
$value = mysql_real_escape_string($_POST['status'][$i]);
$totalClasses = $value;
if($value == 1) //check if present
{
$sql="INSERT INTO `attendence_student` (department_name,courseName,semester,present,absent,total_classes) VALUES('$dptname','$courseName','$stdSemester','$value',0,0)";
}
else //if absent
{
$sql="INSERT INTO `attendence_student` (department_name,courseName,semester,present,absent,total_classes) VALUES('$dptname','$courseName','$stdSemester',0,'$value',0)";
}
$insrt = mysql_query($sql) or die(mysql_error());

Displaying mysql data through hidden field values

I am trying to display mysql records through hidden field values, but nothing displays.
A little help!
Here's the code;
Html:
<form name="form11" method="post" action="hpdata.php" enctype="multipart/form-data">
<input name="pro" id="pro" type="hidden" value= "CMS" />
<input name="piror" id="piror" type="hidden" value= "P1" />
<input name="stat" id="stat" type="hidden" value= "In Progress" />
<input type="submit" name="submit" id="submit" class="groovybutton" value="...">
</form>
PHP:
<?php
$project = $_POST["pro"];
$pirority = $_POST["piror"];
$status = $_POST["stat"];
mysql_connect ("one", "two", "three");
mysql_select_db ("wsms");
$rest = mysql_query("SELECT * FROM sheet WHERE project='$project' AND
pirority='$pirority' AND status='$status'");
while($row = mysql_fetch_array($rest))
{
echo $row['id'] . " " . $row['date']; echo "<br>";
}
?>
Put isset into your php code
Example
<?php
if(isset($_POST['submit'])){
echo $project = $_POST["pro"]."<br>";
echo $pirority = $_POST["piror"]."<br>";
echo $status = $_POST["stat"];
/* mysql_connect ("one", "two", "three");
mysql_select_db ("wsms");
$rest = mysql_query("SELECT * FROM sheet WHERE project='$project' AND
pirority='$pirority' AND status='$status'");
while($row = mysql_fetch_array($rest))
{
echo $row['id'] . " " . $row['date']; echo "<br>";
}*/
}
?>
<form name="form11" method="post" action="" enctype="multipart/form-data">
<input name="pro" id="pro" type="hidden" value= "CMS" />
<input name="piror" id="piror" type="hidden" value= "P1" />
<input name="stat" id="stat" type="hidden" value= "In Progress" />
<input type="submit" name="submit" id="submit" class="groovybutton" value="...">
</form>
Output
CMS
P1
In Progress
First of all check that if the data is coming in the post or not:
<?php
echo "<pre>";
print_r($_POST);
exit;
?>
If yes than remove the print code i provided , and use extract($_POST); at the top of your PHP code. You query will become like this:
$rest = mysql_query("SELECT * FROM sheet WHERE project='$pro' AND
pirority='$piror' AND status='$stat'");

Update multiple rows with radio button check

I am getting the value for the single tsid for each record, however the checked radio button value is not returned in the array, I just get 0? Any help is appreciated.
PHP:
// Set the timesheets to set status approved/rejected
// find out how many records there are to update
$size = count($_POST['tsid']);
// start a loop in order to update each record
$i = 0;
while ($i < $size) {
// define each variable
$tsid = intval($_POST['tsid'][$i]);
$personnelid = intval($_POST['personnel'][$i]);
print "TSID: " . $tsid . "<br>";
print "TSuser: " . $personnelid . "<br>";
if ($tsid > 0 && $personnelid > 0) {
// do the update and print out some info just to provide some visual feedback
$query = "Update timesheets set status='1' where id= '$tsid' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
}
++$i;
}
mysql_close();
HTML:
<input type="hidden" name="tsid[]" value="<?PHP echo $row['id']; ?>">
<li data-role="fieldcontain">
<a href="tsapprove.php?id=<?PHP echo $row['id']; ?>"><p><?PHP echo $row['personnel']; ?></p>
<p><?PHP echo $row['name']; ?></p>
<p class="ui-li-aside"><strong><?PHP echo $row['totalhrs']; ?> H</strong></p>
<fieldset data-role="controlgroup" data-type="horizontal">
<input type="radio" name="personnel[]" id="1" value="<?PHP echo $row['personnel']; ?>" />
<label for="1">Approve</label>
<input type="radio" name="personnel[]" id="2" value="<?PHP echo $row['personnel']; ?>" />
<label for="2">Reject</label>
</fieldset>
</a>
View Details
</li>
Hopefully you can piece this together:
<?
$size = count($_POST['tsid']);
echo "<pre>";print_r($_POST);echo "</pre>";
$i = 0;
while ($i < $size) {
$tsid = $_POST['tsid'][$i];
$pid = $_POST['personnel_'.$i];
print "TSID: " . $tsid . "<br />";
print "TSuser: " . $pid . "<br />";
$i++;
}
?>
<form method="post">
<!--tsid[0] - $i = 0-->
<input type="hidden" name="tsid[]" value="1" />
<input type="radio" name="personnel_0" value="111" />
<input type="radio" name="personnel_0" value="222" />
<!--tsid[1] - $i = 1-->
<input type="hidden" name="tsid[]" value="2" />
<input type="radio" name="personnel_1" value="333" />
<input type="radio" name="personnel_1" value="444" />
<input type="submit" />
</form>
Basically, the way you are returning personnel doesnt really work. So I simplified this a bit, and basically set the radios for personnel differently. Instead of an array, its setting the actual name with the TSID value.
I hard coded 1 and 2, but you would replace with your $row['id'], as well has the number after "personnel_" would be 0..1..2 etc
Hopefully this helps
edit: few issues with code

PHP can't echo for each array

I am trying to echo out an array using for each but it's not displaying any values. The only values i can echo out is within a second for each.
Can anyone tell me what i'm doing wrong?
What i am trying to echo is the price, item, description etc but i am getting nothing.
If you need to see the output of the array it's here http://operationbraveheart.org.uk/jcart/testshop.php
while ($row = $result->fetch()) {
$superitem[$row['itemid']][] = $row;
}
foreach($superitem AS $subitem) {
list($prodid,$item,$size,$description,$price) = $subitem[0];
if ($count % NUMCOLS == 0) echo "<tr>"; # new row
echo '<td>';
var_dump($subitem);
//Your normal code up until the select box...
echo '<form method="post" action="" class="jcart">
<fieldset>
<input type="hidden" name="jcartToken" value="'.$_SESSION['jcartToken'].'" />
<input type="hidden" name="my-item-id" value="'.$subitem['prodid'].'" />
<input type="hidden" name="my-item-price" value="'.$subitem['price'].'" />
<input type="hidden" name="my-item-url" value="http://yahoo.com" />';
if(count($subitem) > 1) {
echo '<li><select name="my-item-name" id="foo">';
foreach($subitem AS $subsubitem) {
echo "<option value='".$subsubitem['size']."'>".$subsubitem['size']."</option>";
}
echo "</select></li>";
}
else {
echo '<input type="hidden" name="my-item-name" value="'.$subitem['item'].'" />';
}
echo'<li>Price: $<span class="price">'.$subitem['price'].'</span></li>
<li>
<label>Qty: <input type="text" name="my-item-qty" value="1" size="3" /></label>
</li>
</ul>
<input type="submit" name="my-add-button" value="add to cart" class="button" />
</fieldset>
</form>';
echo '</td>';
$count++;
$counter++;
if ($count % NUMCOLS == 0) echo "</tr>\n"; # end row
}
Current it looks like $subitem contains an array of length 1 where the first index is a row. Change...
$superitem[$row['itemid']][] = $row;
should be...
$superitem[$row['itemid']] = $row;
and...
list($prodid,$item,$size,$description,$price) = $subitem[0];
should be...
list($prodid,$item,$size,$description,$price) = $subitem;

Categories