only last row is inserting in database - php

I have purchase order form where I am storing product details in session i.e product name, quantity, rate etc. and saving it to database. And at the time of editing purchase order, getting product details from database and storing it in session and appending new product details to session array. It is working fine. But When I submit form then Only last record i.e. newly added record is inserted in database.
here you can assume that I am editing shopping cart after placing order.
My problem is that add,delete items in cart after placing order is logically correct or not? And if yes then How?
This is my code for save and update purchase order.
function save(&$purchase_data,$purchase_id)
{
$success=false;
//Run these queries as a transaction, we want to make sure we do all or nothing
$this->db->trans_start();
if($purchase_data)
{
if (!$purchase_id or !$this->exists($purchase_id))
{
//$purchase_data['purchase_id'] = $purchase_id = $purchase_data['purchase_id'];
$success = $this->db->insert('purchase_order',$purchase_data);
$post_array['cart']=$this->session->userdata('data');
/*print_r($post_array);
exit;*/
$purchase_id=$this->db->insert_id();
$i=0;
foreach($post_array['cart'] as $item)
{
//echo "<pre>"; print_r($item); echo "</pre>";
$query = $this->db->query("SELECT name FROM phppos_items WHERE item_id='".$item['product_id']."'");
foreach ($query->result() as $row)
{
$product_name=$row->name;
}
$product_id=$item['product_id'];
$quantity=$item['quantity'];
$unit=$item['unit'];
$unit_rate=$item['unit_rate'];
$query = $this->db->query("insert into phppos_productdetails(product_id,product_name,quantity,unit,unit_rate,purchase_id) values ('$product_id','$product_name','$quantity','$unit','$unit_rate','$purchase_id')");
$i++;
}
}
else
{
$this->db->where('purchase_id', $purchase_id);
$success = $this->db->update('purchase_order',$purchase_data);
//$this->session->set_userdata('sess_products');
$post_array['cart']=$this->session->userdata('sess_products');
$i=0;
foreach($post_array['cart'] as $item)
{
echo "<pre>"; print_r($item); echo "</pre>";
$query = $this->db->query("SELECT name FROM phppos_items WHERE item_id='".$item['product_id']."'");
foreach ($query->result() as $row)
{
$product_name=$row->name;
}
$product_id=$item['product_id'];
$quantity=$item['quantity'];
$unit=$item['unit'];
$unit_rate=$item['unit_rate'];
$query = $this->db->query("update phppos_productdetails set product_id='$product_id',product_name='$product_name',quantity='$quantity',unit='$unit',unit_rate='$unit_rate' where purchase_id='$purchase_id'");
$i++;
}
}
}
$this->db->trans_complete();
return $success;
}

you have put (where purchase_id='$purchase_id'")
so when the loop executes last time it updates all records with purchase_id as $purchase_id

Your query:
$query = $this->db->query("update phppos_productdetails set product_name='$product_name',product_id='$product_id',quantity='$quantity',unit='$unit',unit_rate='$unit_rate' where purchase_id='$purchase_id'");"
By seeing above query the parameters used in this query like $product_name is out of inner foreach scope.Hence it takes only last record and insert it into database.
If you place this query in inner foreach loop then it will inserts appropriate records as per you required.
Hope this will helps you.

Related

fetch and check cart data with php mysql

I had cart data in session like product_id, product_name, product_price..... so there is multiple data in session with array it's not fixed..sometime single data and sometime morethan one..... but when customer check out.... I need to check each product with customers entered pincode …..and products have multiple or single pincode in table....so we can get them by session product_id ..... then want to check if those pin match with client/user pincode then store in new session and those products which are not match yet....also move in another new session..... or just want to display product like allowed or not allowed product for this pin
is there any way to make it simple ? i think it's work with foreach inside condtions and all..but still confused.....sorry for bad english !
i had just wrote little code but confused what to next ?
if (!empty($_SESSION["shopping_cart"])){
foreach ($_SESSION["shopping_cart"] as $keys => $value){
$pro_session_id = $_SESSION["shopping_cart"][$keys]['product_id'];
$select_price_data = mysql_query("select * from product_pincode where product_ID = '$pro_session_id'");
}
}
if (!empty($_SESSION["shopping_cart"])) {
foreach ($_SESSION["shopping_cart"] as $keys => $value) {
$pro_session_id = $_SESSION["shopping_cart"][$keys]['product_id'];
// echo $pro_session_id;
// echo "<br>";
// $select_pin_data = mysql_query("select * from product_pincode where product_ID = '$pro_session_id'");
$select_pin_query = "SELECT * FROM product_pincode WHERE product_ID = '$pro_session_id'";
$selected = mysql_query($select_pin_query, $con) or die(mysql_error($con));
$pin_val = array();
while ($get_pin_data = mysql_fetch_assoc($selected)) {
$pin_val[] = $get_pin_data;
}
foreach ($pin_val as $get_pin_data) {
if ($get_pin_data['pincode_number'] == $_SESSION["order_placement_details"][0]['user_pincode']) {
echo "Complete " . $get_pin_data['pincode_number'];
echo "<br>";
} else {
echo "unallowed" . $get_pin_data['pincode_number'];
echo "<br>";
}
}
}

Updating a 4th table using 3 different tables

I've got 3 different tables and I want to update the 4th table with some specific column from each of the 3 tables, they all have a common key. I can do this from the phpmyadmin, but I want to do it using a php script.
This is what I tried but it didn't work
if (isset($_GET)) {
$update = '';
$count="SELECT * FROM test2 ";
foreach ($connect->query($count) as $row) {
$term_total1=$row['english'];
$sql = "UPDATE total set `f_test` ='$term_total1' ";
foreach ($connect->query($count) as $row) {
echo "success<br>" . $term_total1;
}
}
}else{
echo "try another method" . mysqli_error($connect);
}
Have been trying for days now.
Repeated the same code for the other two tables but it won't work.
Is it possible to do it in a single query? If Yes, then how
I'm pretty sure your method of using foreach to loop the result set is incorrect. In your updated code you've also not got a unique identifier so your code is just going to mass update your table. Here's your current code fixed up so hopefully you can understand how to loop the dataset from mysqli
$count="SELECT * FROM test2";
if($res = $connect->query($count)){
while($row = $res->fetch_assoc()){
$term_total1 = $row['english'];
$sql = "UPDATE total set `f_test` = '{$term_total1}'";
if($res2 =$connect->query($sql)){
echo "success<br>" . $term_total1;
}else{
print_r($connect->error());
}
}
}else{
print_r($connect->error());
}

Add a product to a shopping cart/favourites php

I am trying to allow users to add destinations to their favourites page, similar to adding products to a shopping cart. I am doing this by saving the destinations to a session array and then adding this session array onto the end of an SQL SELECT statment to print the destinations. Although the code I have written only allows me to add one destination to favourites. Can anyone point my in the right direction.
if(empty($_SESSION['cart'])){
$_SESSION['cart'] = array();
} else {
array_push($_SESSION['cart'], $_GET['theid']);
// HOW TO LOOP THROUGH SESSION CART
$str = implode(',', $_SESSION['cart']) ;
$query = "SELECT * FROM Destinations WHERE DestID IN ($str)" ;
$result = mysqli_query($connection, $query);
while($row=mysqli_fetch_assoc($result)){
echo $row['DestName'].' '.$row['DestRating'].
' <img src="Images/'.$row['DestImage'].'" /> <br/>';
}
}

echo key value from a row before postgres php while loop

Can't believe this is giving me a problem but here it is. An example of the query and code is:
$sql = "SELECT
o.order_id, o.order_number, o.broker_id, o.agent_id
FROM orders o";
$sql_res = safe_query($sql);
/* I want to echo broker_id and angent_id only once here,
before the while loop, because the values are all the same */
while ($row = pg_fetch_array($sql_res)){
echo $order_number;
}
Assume broker and agent id numbers are each the same in every row. I don't want to echo them every time in the loop. I just want them to echo one time before the loop. Since they are the same, it does not matter which row they are echoed from.
I figured out a different way for a means to an end. It works well.
$sql = "SELECT
o.order_id, o.order_number, o.broker_id, o.agent_id
FROM orders o";
$sql_res = safe_query($sql);
$count = 0;
while ($row = pg_fetch_array($sql_res)){
if ($count == 0) {
echo $broker_id;
echo $agent_id;
}
echo $order_number;
$count += 1;
}
I realize I'm echoing the broker and agent IDs inside the while loop, but it's only an echo the first time through, and I can display them at top. And then every unique order is echoed. Visually, it accomplished what was needed for the end user.

How to select a array of rows from db and update them with another array of data

I'm developing a trading card game in unity and need some help with the PHP and MySQL side of things.
My database structure is something like this. This is set up when the player registers. Each player has 60 rows inside of player_deck because the decks limit is 60.
players
player_id/email/password/username
player_deck
player_id/card_id/card_amount
I'm trying to update these rows when the player saves the deck. From Unitys end I'm calling a URL that looks something like this.
"localhost/saveplayerdata/saveplayerdeck.php?playerid=&deckcardids=&deckcardamounts="
The PHP page stores the deckcardids and deckcardamounts into two arrays.
Now here is where I'm stuck. I need to get all the rows that belong to that player and update them with our data sent from Unity.
This is what I have so far. I'm able to select the rows I need but how would I go about updating them with the data in my arrays? Thanks for reading.
EDIT: Added my query to update. This updates all the rows. I need it to only update the current row that being looped through with the index that deckCardIds is at. I know my update query is wrong but I'm not sure of the correct syntax to use so that I'm only effecting the row I'm on.
<?php
$playerId = $_GET['playerid'];
$playerDeckCardIds = $_GET['deckcardids'];
$playerDeckCardAmounts = $_GET['deckcardamounts'];
$deckCardIds = explode(" ", $playerDeckCardIds);
array_pop($deckCardIds);
$deckCardAmounts = explode(" ", $playerDeckCardAmounts);
array_pop($deckCardAmounts);
//This is the new array of cardIds sent from Unity
//foreach ($deckCardIds as $value)
//{
//echo "Deck Card Id $value <br>";
//}
//This is the new array of cardAmounts sent from Unity
// foreach ($deckCardAmounts as $value)
//{
//echo "Deck Card Amount $value <br>";
//}
try
{
#Connect to the db
$conn = new PDO('mysql:host=localhost;dbname=tcg', 'root', '');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT card_id, card_amount FROM player_deck WHERE player_id = :player_id');
$stmt->execute(array('player_id' => $playerId));
$r = $stmt->fetchAll(PDO::FETCH_OBJ);
$i = 0;
#If we have a result
if (count($r))
{
foreach ($r as $row)
{
$stmt = $conn->prepare('UPDATE player_deck SET card_id = :card_id WHERE player_id = :player_id');
$stmt->bindParam(':player_id', $playerId);
$stmt->bindParam(':card_id', $deckCardIds[$i]);
$stmt->execute();
$i ++;
}
}
} catch (PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
?>

Categories