How to make cart not duplicate items? - php

I need to know How to not make item duplicate and add quantity from showitem.php to quantity
but I made update to table in sql but nothing happen to the table I don't know why ?
This is addtocart.php
<?php
session_start();
function addtocart($id,$qty){
if (isset($id)){
//connect to database
$mysqli = mysqli_connect("localhost", "root", "", "e-com");
//create safe values for use
$safe_sel_item_id = mysqli_real_escape_string($mysqli,
$id);
$safe_sel_item_qty = mysqli_real_escape_string($mysqli,$qty);
//validate item and get title and price
$get_iteminfo_sql = "SELECT itemname FROM items WHERE itemid = '".$safe_sel_item_id."'";
$get_iteminfo_res = mysqli_query($mysqli, $get_iteminfo_sql)
or die(mysqli_error($mysqli));
if (mysqli_num_rows($get_iteminfo_res) < 1) {
//free result
mysqli_free_result($get_iteminfo_res);
//close connection to MySQL
mysqli_close($mysqli);
//invalid id, send away
header("Location: seestore.php");
exit;
} else {
//get info
while ($item_info = mysqli_fetch_array($get_iteminfo_res)) {
$item_title = stripslashes($item_info['itemname']);
}
//free result
mysqli_free_result($get_iteminfo_res);
$sql = "select sel_item_qty from shooppertrack where sel_item_id = '" .
$safe_sel_item_id . "'";
$res = mysqli_query($mysqli, $sql);
while ($res_info = mysqli_fetch_array($get_iteminfo_res)){
$update_qty = $res['sel_item_qty'];
}
// does quantity exist?
if (mysqli_num_rows($res) > 0 ) {
// get sel_item_qty, add 1, run update query
"UPDATE shooppertrack SET sel_item_qty = sel_item_qty + $update_qty
WHERE sel_item_id = '" .$safe_sel_item_id . "'" ;
} else {
//add info to cart table
$addtocart_sql = "INSERT INTO shooppertrack
(session_id, sel_item_id, sel_item_qty,
date_added)
VALUES ('".$_COOKIE['PHPSESSID']."',
'".$safe_sel_item_id."',
'".$safe_sel_item_qty."',
now())";
$addtocart_res = mysqli_query($mysqli, $addtocart_sql)
or die(mysqli_error($mysqli));
}
//close connection to MySQL
mysqli_close($mysqli);
//redirect to showcart page
header("Location: showcart.php");
exit;
}
} else {
//send them somewhere else
header("Location: seestore.php");
exit;
}
}
addtocart($_POST['sel_item_id'],$_POST['sel_item_qty']);
?>
This is showitem.php
<?php
function show($x){
//connect to database
$mysqli = mysqli_connect("localhost", "root", "", "e-com");
$display_block = "<h1>My Store - Item Detail</h1>";
//create safe values for use
$safe_item_id = mysqli_real_escape_string($mysqli, $x);
//validate item
$get_item_sql = "SELECT c.cat_id , c.cat_name, si.itemid, si.itemname,
si.price, si.descripition, si.photo FROM items
AS si LEFT JOIN categories AS c on c.cat_id = si.cat_id
WHERE si.itemid = '".$safe_item_id."'";
$get_item_res = mysqli_query($mysqli, $get_item_sql)
or die(mysqli_error($mysqli));
if (mysqli_num_rows($get_item_res) < 1) {
//invalid item
$display_block .= "<p><em>Invalid item selection.</em></p>";
} else {
//valid item, get info
while ($item_info = mysqli_fetch_array($get_item_res)) {
$cat_id = $item_info['cat_id'];
$cat_title = strtoupper(stripslashes($item_info['cat_name']));
$item_title = stripslashes($item_info['itemname']);
$item_price = $item_info['price'];
$item_desc = stripslashes($item_info['descripition']);
$item_image = $item_info['photo'];
}
//make breadcrumb trail & display of item
$display_block .= <<<END_OF_TEXT
<p><em>You are viewing:</em><br/>
<strong>$cat_title > $item_title</strong></p>
<div style="float: left;"><img src="$item_image" alt="$item_title" /></div>
<div style="float: left; padding-left: 12px">
<p><strong>Description:</strong><br/>$item_desc</p>
<p><strong>Price:</strong> \$$item_price</p>
<form method="POST" action="addtocart.php">
END_OF_TEXT;
//free result
mysqli_free_result($get_item_res);
$display_block .= "
<p><label for=\"sel_item_qty\">Select Quantity:</label>
<select id=\"sel_item_qty\" name=\"sel_item_qty\">";
for($i=1; $i<11; $i++) {
$display_block .= "<option value=\"".$i."\">".$i."</option>";
}
$display_block .=<<<ENDOFTEXT
</select><p>
<input type="hidden" name="sel_item_id" value="$_GET[itemid]" />
<button type="submit" name="submit" value="submit">Add to Cart</button>
</form>
</div>
ENDOFTEXT;
}
return $display_block;
//close connection to MySQL
mysqli_close($mysqli);
}
?>

You need to query your cart for that item and session before inserting. If it exists, you should update the quantity instead.
$sql = 'select sel_item_qty from shooppertrack where sel_item_id = ' .
$safe_sel_item_id . ' and session_id = ' $_COOKIE['PHPSESSID'];
$res = mysqli_query($mysqli, $sql);
// does quantity exist?
if (mysqli_num_rows($res) > 0 ) {
// get sel_item_qty, add 1, run update query
} else {
// run your insert query
}

Try this
//add info to cart table
$sql = "Select session_id, sel_item_id from shooppertrack where session_id = $sid and sel_item_id = $si_id";
$res = mysqli_query($mysqli, $sql);
if(mysqli_num_rows($res) == 1)
{
// update with qty +1;
}else{
$addtocart_sql = "INSERT INTO shooppertrack
(session_id, sel_item_id, sel_item_qty,
date_added)
VALUES ('".$_COOKIE['PHPSESSID']."',
'".$safe_sel_item_id."',
'".$safe_sel_item_qty."',
now())";
$addtocart_res = mysqli_query($mysqli, $addtocart_sql)
or die(mysqli_error($mysqli));
}

Related

HOW TO GET QUERY IN SQL USING PHP IN SQL TIGGERING

This is my code my $sql variable didn't give query plese help me for this I try this but I couldn't please help me with that
<?php
$connect = mysqli_connect("localhost", "root", "", "finger");
$f= "";
$l= "";
$sql = "CREATE TRIGGER `ersdmmmmecv` AFTER INSERT ON `event` FOR EACH ROW SELECT fname,Lname INTO $f,$l FROM user WHERE id=NEW.id;"
$result = mysqli_query($connect, $sql);
?>
You cannot use a MySQL trigger to update PHP variables. If you want the values of $f and $l to update whenever a new record is inserted into your event table, you need to do this in PHP entirely.
Something along these lines should work (note: I did not test this myself):
$f = "";
$l = "";
$new_id = "id_value";
$insert = $connect->prepare("INSERT INTO `event` (`id`, `column2`, `column3`) VALUES (?, ?, ?)");
$insert->bind_param("sss", $new_id, "value2", "value3");
if ($insert->execute() === FALSE) {
echo 'Could not insert event: ' . $insert->error;
} else {
// If `event`.`id` is actually an AUTO_INCREMENT column, and you don't
// specify it in your INSERT query, use this here:
// $new_id = $insert->insert_id;
$select = $connect->prepare("SELECT `fname`, `Lname` FROM `user` WHERE `id` = ?");
$select->bind_param("s", $new_id);
$select->execute();
$select->bind_result($f, $l);
$success = $select->fetch();
if ($success !== TRUE) {
echo 'Could not update $f and $l with new values: '
. ($select->error ?: 'No user with id: ' . $new_id);
}
}
If you have multiple places in your code where you insert data into the events table, I would personally wrap this in a function so I wouldn't have to repeat this every time.
This is the Trigger Solution
<?php
$connect = mysqli_connect("localhost", "root", "", "finger");
$sql1 = "CREATE TRIGGER `ersdmmmmecv` AFTER INSERT ON `event` FOR EACH ROW INSERT INTO res (fres,lres) VALUES SELECT fname,Lname FROM user WHERE id=NEW.id;";
$result2 = mysqli_query($connect, $sql1);
$sql = "SELECT * FROM res;";
if( !( $selectRes = mysqli_query($connect, $sql) ) ){
echo 'Retrieval of data from Database Failed - #';
}else{
?>
<table border="2">
<thead>
<tr>
<th>fName</th>
<th>lname</th>
</tr>
</thead>
<tbody>
<?php
if( mysqli_num_rows( $selectRes )==0 ){
$print_output= '<tr><td colspan="4">No Rows Returned</td></tr>';
}else{
while( $row = mysqli_fetch_assoc( $selectRes ) ){
$print_output="<tr><td>{$row['fres']}</td><td>{$row['lres']}</td></tr>\n";
}
}
?>
</tbody>
</table>
<?php
try
{
$fp=pfsockopen("127.0.0.1", 80);
fputs($fp, $print_output);
fclose($fp);
echo 'Successfully Printed '.$print_output;
}
catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
<?php
}
?>
<?php
$sql2= "DROP TRIGGER ersdmmmmecv";
$result1 = mysqli_query($connect, $sql2);
$sql3= "DELETE FROM res;";
$result3 = mysqli_query($connect, $sql3);
?>
<script>
setTimeout(function () { window.location.reload(); }, 1*60*1000);
// just show current time stamp to see time of last refresh.
document.write(new Date());
</script>

php MySql global variable

I'm trying to get the last order id and set it in variable so I'll be able to set this id in another Order_Items table
$generatedId=0;
if(isset($_POST['newOrder'])){
$costumerID = $_POST['CostumerID'];
$orderDateID = $_POST['orderDateID'];
$deliveryDateID = $_POST['deliveryDateID'];
$orderRemeraks = $_POST['orderRemeraks'];
$orderType = $_POST['orderType'];
echo $costumerID;
$query = "INSERT INTO `orders` (`costumerName`,`dateOfOrder`,`dateOfDelivery`,`remarks`,`type`,`status`)
VALUES ('$costumerID','$orderDateID','$deliveryDateID','$orderRemeraks','$orderType', 'open');";
$insertRow = $mysqli->query($query) or die ($mysqli->error.__LINE__);
$generatedId = $mysqli->insert_id;
if($insertRow){
$GLOBALS['generatedId'] = $mysqli->insert_id;
$msg = 'New Order was added ';
echo $msg;
echo $generatedId;
}
}
if(isset($_POST['newItem'])){
$item_Number = $_POST['item_Number'];
$itemQty = $_POST['itemQty'];
$itemKg = $_POST['itemKg'];
$itemRemarks = $_POST['itemRemarks'];
echo $generatedId;
$query = "INSERT INTO `item_number` (`order_id`, `item_number`, `quantity`,`quantity_kg`,` remarks`,`filling_status`)
VALUES('$generatedId', '$item_Number','$itemQty','$itemKg','$itemRemarks','not',);";
$insertRow = $mysqli->query($query) or die ($mysqli->error.__LINE__);
if($insertRow){
echo 'New Item was added ' ;
}
}
The problem is the $genertedId is printed with the initial 0 and there for I can't put it in the order_items table, but in the first time(right after echo $msg, when printing it it's returning the true value;
thank you
$generatedId = mysqli_insert_id($mysqli);
if($insertRow){
$GLOBALS['generatedId'] = $generatedId;
$msg = 'New Order was added ';
echo $msg;
echo $generatedId;
}

perform two computation in two column and the answer will be save in another column

How can I perform a autocompute in my database ex. the value of Stock and Quantity(Quantity-Stock) the answer will be save in CarryO column
create.php
<?php
require_once 'dbconfig.php';
$con = mysql_connect("localhost","root","");
if($con)
{
mysql_select_db("testproduct",$con);
}
if($_POST)
{
$sql = mysql_query("SELECT * FROM tblproduct WHERE id = '".$_POST['pid']."'");
$prod = mysql_fetch_array($sql);
$pname = $prod['name'];
$actualprice = $prod['actualprice'];
$sellprice = $prod['sellprice'];
$stock = $prod['Stock'];
$gname = $_POST['gname'];
$saledate = $_POST['saledate'];
$quantity = $_POST['quantity'];
$profit = $_POST['profit'];
$carryO = $_POST['carryO'];
$sells = $_POST['sells'];
$expense = $_POST['expense'];
try{
$stmt = $db_con->prepare("INSERT INTO tblsales(pname,gname,saledate,quantity,actualprice,sellprice,carryO,sells,expense,profit,stock)
VALUES(:upname,:ugname,:usaledate,:uquantity,:uactualprice,:usellprice,:ucarryO,:usells,:uexpense,:uprofit,:ustock)");
$stmt->bindParam(":upname", $pname);
$stmt->bindParam(":ugname", $gname);
$stmt->bindParam(":usaledate", $saledate);
$stmt->bindParam(":uquantity", $quantity);
$stmt->bindParam(":uactualprice", $actualprice);
$stmt->bindParam(":usellprice", $sellprice);
$stmt->bindParam(":ucarryO", $carryO);
$stmt->bindParam(":usells", $sells);
$stmt->bindParam(":uexpense", $expense);
$stmt->bindParam(":uprofit", $profit);
$stmt->bindParam(":ustock", $stock);
if($stmt->execute())
{
echo "Successfully Added";
}
else{
echo "Query Problem";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
thanks for your help just new in php and please let me know if I can use your code or its only a example
Change this part:
$prod = mysql_query("SELECT * FROM tblproduct WHERE id = ".$_POST['pid']);
echo $prod;
$pname = [$prod['name']];
Into:
$sql = mysql_query("SELECT * FROM tblproduct WHERE id = '".$_POST['pid']."'");
$prod = mysql_fetch_array($sql);
$pname = $prod['name'];
You may want to try this.
$prod = mysql_query("SELECT * FROM tblproduct WHERE id = ".$_POST['pid'],$db_con); //$db_con must be your database connection
if(!$prod) { die("Database query failed: " . mysql_error()); } //always check if your query is properly done.
$pname = "";
while ($row = mysql_fetch_array($prod)) {
$pname = $row["name"]; }
also if you are fetching only one column which is the name then be specific to your query for fastest result. e.g. "SELECT name FROM tblproduct WHERE id = ".$_POST['pid']

Problems updating correct row in databse with php

I'm trying to create a voting system for artists played on my radio station. I'm using the source code from: http://dl.howcode.org/download/97ff383c7d4dc9939c65c9e6fab2a5dc
The problem I have found is that the votes update using the number from the first row in the database no matter which option is selected, thus if for instance the first row has 3 votes in and the user tries to vote on someone with 0 votes, it will change the votes for the correct artist to 4 instead of 1... I hope that makes sense?
The code I have is:
[EDIT] I have changed the queries to fetch assoc to make it easier to understand.
<?php
$voteID = $_GET['voteID'];
$connect = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx');
$query = "SELECT * FROM listenervotes WHERE voteID='$voteID'" ;
$q = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($q)){
$id = $row["id"];
$voteTitle = $row["voteTitle"];
$voteID = $row["voteID"];
$ipaddress = $row["ipAddress"];
echo "<h3>$voteTitle</h3>";
?>
<table>
<form action="" method="POST">
<?php
$artists = "SELECT * FROM artists WHERE voteID='$voteID'" ;
$q2 = mysqli_query($connect, $artists);
while($r = mysqli_fetch_assoc($q2)){
$artist = $r["artistName"];
$votes = $r["votes"];
$genre = $r["genre"];
$ip = $_SERVER['REMOTE_ADDR'];
$newIpAddress = $ipaddress."$ip, ";
$newVotes = $votes + 1;
if (isset($_POST['vote'])) {
$voteOption = $_POST['voteOption'];
if ($voteOption == ""){
die("You haven't selected anyone!");
}else{
$ipaddressE = explode(",", $ipaddress);
if(in_array($ip, $ipaddressE)){
die("You have already voted!");
}else{
mysqli_query($connect, "UPDATE artists SET votes='$newVotes' WHERE voteID='$voteID' AND artistName='$voteOption'");
mysqli_query($connect, "UPDATE listenervotes SET ipaddress='$newIpAddress' WHERE voteID='$voteID'");
die('You voted successfully!<br><tr><td>'.$artist.'</td><td>'.$genre.'</td><td>'.$votes.' Votes</td></tr>');
}
}
}
echo '<tr><td>'.$artist.'</td><td>'.$genre.'</td><td><input type="radio" name="voteOption" value="'.$artist.'"</td></tr>';
}
}
?>
I could be missing something obvious, in my mind I'm thinking that I somehow need to iterate through the rows before setting the new value, if so, how and where?
It looks like you are always looping over all rows and updating the relevant row with the first value found. Adding a check on the ID should do:
<?php
$voteID = $_GET['voteID'];
$connect = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx');
$query = "SELECT * FROM listenervotes WHERE voteID='$voteID'" ;
$q = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($q)){
$id = $row["id"];
$voteTitle = $row["voteTitle"];
$voteID = $row["voteID"];
$ipaddress = $row["ipAddress"];
echo "<h3>$voteTitle</h3>";
?>
<table>
<form action="" method="POST">
<?php
$artists = "SELECT * FROM artists WHERE voteID='$voteID'" ;
$q2 = mysqli_query($connect, $artists);
while($r = mysqli_fetch_assoc($q2)){
$artist = $r["artistName"];
$votes = $r["votes"];
$genre = $r["genre"];
$ip = $_SERVER['REMOTE_ADDR'];
$newIpAddress = $ipaddress."$ip, ";
$newVotes = $votes + 1;
if (isset($_POST['vote'])) {
$voteOption = $_POST['voteOption'];
if ($voteOption == ""){
die("You haven't selected anyone!");
}else{
$ipaddressE = explode(",", $ipaddress);
if(in_array($ip, $ipaddressE)){
die("You have already voted!");
}elseif ($voteOption === $artist) { // Don't run UPDATE when we're on the wrong row.
mysqli_query($connect, "UPDATE artists SET votes='$newVotes' WHERE voteID='$voteID' AND artistName='$voteOption'");
mysqli_query($connect, "UPDATE listenervotes SET ipaddress='$newIpAddress' WHERE voteID='$voteID'");
die('You voted successfully!<br><tr><td>'.$artist.'</td><td>'.$genre.'</td><td>'.$votes.' Votes</td></tr>');
}
}
}
echo '<tr><td>'.$artist.'</td><td>'.$genre.'</td><td><input type="radio" name="voteOption" value="'.$artist.'"</td></tr>';
}
}
?>

$key=$_REQUEST['key'] doesnt work

if (isset($_POST['cancel'])) {
print("<script>location.href = 'task_led.php'</script>");
}
else if (isset($_POST['assign'])) {
$atask = $_POST['task'];
$table_task = $_POST['hid_task'];
$key = $_REQUEST['key'];
include 'sql.php';
$SQL = " ALTER TABLE $table_task ADD $atask VARCHAR(255) NOT NULL";
mysql_query($SQL);
$SQL = "UPDATE info SET individ_task = '$atask' WHERE username = '$key'";
mysql_query($SQL);
$SQL = "INSERT INTO $table_task (`username`, $atask) VALUES ('$key', 'pending')";
mysql_query($SQL);
$SQL = "UPDATE info SET task_status_indi = 'pending' WHERE username = '$key'";
mysql_query($SQL);
mysql_close($db_handle);
print("<script>location.href = 'task_led.php'</script>");
}
else{
$namekey = $_REQUEST['key'];
$user = $_SESSION['username'];
include 'sql.php';
$SQL = "SELECT * FROM info WHERE username = '$user'";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
$grp = $db_field['groups'];//telephone_tech
$tsk = $db_field['group_task'];//resolve_telephone
}
print("<div style='top:167; left:380; position:absolute; z-index:1;'>");
print("<table border = '0' width = '370' bgcolor = 'white'>");
print("<tr><td>$tsk</td></tr>");
print("</table>");
print("</div>");
$SQL = "SELECT * FROM task_list WHERE taskname = '$tsk'";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
$dsc = $db_field['ds'];
}
print("<div style='top:200; left:250; position:absolute; z-index:1;'>");
print("<font face='Broadway' size = '4'>Description:</font>");
print("</div>");
print("<div style='top:197; left:380; position:absolute; z-index:1;'>");
print("<table border = '0' width = '370' bgcolor = 'white'>");
print("<tr><td>$dsc</td></tr>");
print("</table>");
print("</div>");
print("<div style='top:270; left:350; position:absolute; z-index:1;'>");
print("<form name='add_form' method='post' action='add_task_led.php'>");
print("<table border = '0' >");
print("<tr><td><b>Name:</b></td>");
print("<td><input name = 'uname' type = 'text' readonly = 'true' value = $namekey></td>");
print("</tr>");
print("<tr><td><b>Task:</b></td>");
print("<td><input name = 'task' type = 'text' value = ''></td>");
print("<input name = 'hid_task' type = 'hidden' value = $tsk>");
print("</tr>");
print("<tr>");
print("<td align = 'right'><input name = 'reset' type = 'reset' value = 'reset'></td>");
print("<td><input name = 'cancel' type = 'submit' value = 'cancel'>");
print("<input name = 'assign' type = 'submit' value = 'ASSIGN'></td>");
print("</tr>");
print("</table>");
print("</form>");
print("</div>");
mysql_close($db_handle);
}
I need help with this one it is supposed to get the key from URL like nbproject/add_task_led.php?key=Marija to put it in $key variable and it doesn't seem to work. When I put the name directly in this example Marija instead of $key it changes the DB. Am I doing something wrong?
For testing purposes
Can you setup a test table with the following code that I concluded as being successful.
Be sure to change these variables to fit your own, or create them as shown:
$table_task = "table_task"; // table name
$atask = "a_task"; // column name
$db_selected = mysql_select_db('db_name', $db); // db_name is your DB
HTML/PHP/SQL (form action is set to self)
<?php
if (!empty($_REQUEST['key'])) {
$key = $_REQUEST['key'];
echo "key: ". $key. "\n";
$db = mysql_connect("host","username", "password");
$db_selected = mysql_select_db('db_name', $db);
if (!$db_selected) {
die ('Can\'t use it : ' . mysql_error());
}
$table_task = "table_task";
$atask = "a_task";
$SQL = "INSERT INTO $table_task (`username`, $atask) VALUES ('$key', 'pending')";
mysql_query($SQL,$db);
// Used for my own testing purposes that you can comment out
// $SQL = "UPDATE $table_task SET a_task = 'pending_test' WHERE username = '$key'";
// mysql_query($SQL,$db);
}
?>
<!DOCTYPE html>
<html>
<head>
<body>
<form action="" method="get">
User: <input type="text" name="key" /><br />
<input type="submit" value="Send" />
</form>
</body>
</html>

Categories