Update SQL query from post data - mysql

I've script with import csv and column mapping.
After mapping column .csv in html table I need udate data.
I try write this script:
$file_data = $_SESSION['file_data'];
unset($_SESSION['file_data']);
foreach($file_data as $row)
{
$data[] = '("'.$row[$_POST["sku"]].'", "'.$row[$_POST["stock"]].'")';
}
if(isset($data))
{
$query = "
UPDATE products
SET (sku, stock)
VALUES ".implode(",", $data)."
WHERE sku = ".$row[$_POST["sku"]]."
";
$statement = $connect->prepare($query);
if($statement->execute())
{
echo 'Data Updated Successfully';
}
}
But I have problem with construct correct and valid udate query:
$query = "
UPDATE products
SET (sku, stock)
VALUES ".implode(",", $data)."
WHERE sku = ".$row[$_POST["sku"]]."
";
I try also in this way but still something went wrong:
$file_data = $_SESSION['file_data'];
unset($_SESSION['file_data']);
foreach($file_data as $row)
{
$query = "
UPDATE products
SET sku = '.$row[$_POST["sku"]].', stock = '.$row[$_POST["stock"]].'
WHERE sku = '.$row[$_POST["sku"]].'
";
$statement = $connect->prepare($query);
I try also:
$file_data = $_SESSION['file_data'];
unset($_SESSION['file_data']);
foreach($file_data as $row)
{
$data1[] = '("'.$row[$_POST["sku"]].'")';
$data2[] = '("'.$row[$_POST["stock"]].'")';
}
if(isset($data, $data2))
{
$query = "
UPDATE products
SET stock = ".implode(",", $data2)."
WHERE sku = ".implode(",", $data)."
";
$statement = $connect->prepare($query);
if($statement->execute())
{
echo 'Data Updated Successfully';
}
}
I need update values stock with rule where sku = and here post values sku from csv file

Related

Update same tables from from select value from same table mysql

i am trying to update a table column which same column from same table select.
Here is the code (updated)
public function UpdateStockIn($id, $subUnitValue) {
$query = "UPDATE BRAND_LIST SET CURRENT_STOCK_BOTTLE = (SELECT CURRENT_STOCK_BOTTLE FROM BRAND_LIST WHERE ID = ?) + '.$subUnitValue.' WHERE ID = ? ";
$success = 0;
try {
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $id);
$stmt->bindParam(2, $id);
$stmt->execute();
$success = 1;
} catch (PDOException $ex) {
echo $ex->getMessage();
}
return $success;
}
it Show error like this
You can't specify target table 'BRAND_LIST' for update in FROM clause
Try run these 2 sqls, The first one will store a value into mysql local variable then use into 2nd sql.
SELECT #old_subUnitValue := GROUP_CONCAT(table1.CURRENT_STOCK_BOTTLE) FROM BRAND_LIST AS table1 WHERE table1.ID=2;
UPDATE BRAND_LIST AS table2 SET table2.CURRENT_STOCK_BOTTLE = #old_subUnitValue + '.$subUnitValue.' WHERE table2.ID=2;
Use the below query
$query = "UPDATE BRAND_LIST SET CURRENT_STOCK_BOTTLE = CURRENT_STOCK_BOTTLE + ".$subUnitValue." WHERE ID = ?";

How can i increment +1 to the value in database using update

Here i am trying to increment the value in database by + 1.for example
here in database i have value 3 in one column by name owners now when i call the below function. i want to increment the column by +1 i.e the column value now should become 4
function updateOwners($product_id){
// Create connection
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE product_list set product_current_co_owners = where product_id ='$product_id'";
$result = $conn->query($sql);
/*if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<b>Total co-owners:</b><br><span>'.$row["product_co_owners"].'</span>';
}
} else {
echo "No data available";
}*/
$conn->close();
}
how can i do this?
$sql = "UPDATE product_list set product_current_co_owners =# here i want add +1 to previous value where product_id ='$product_id'";
Just add +1 to the previous value like
UPDATE product_list
set product_current_co_owners = product_current_co_owners + 1
where product_id ='$product_id';
Try this but your column must be integer type
UPDATE product_list set product_current_co_owners =product_current_co_owners+1 where product_id ='$product_id'
$sql = "UPDATE product_list set product_current_co_owners = owners + 1 where product_id ='$product_id'";

SQL update not committed

I am having a weird issue but I do not understand what is happening. I amcreated a function to update up to three columns (end_plan_date, balance and server) in a table (user) and 2 inserts in another table.
For some reason, my last update (column server of the user table) is not committed ($query = mysql_query("UPDATE user SET server='$serv' WHERE email='$subemail'");) unless I give a value for at leat one of the two other values ($subamt or $subday).
Do you know why this query is not updating the user table with the server value I parsed?
function addBalance($subemail, $subamt,$subday,$userid,$serv) {
$q = "SELECT * FROM user WHERE email = '$subemail'";
$result = mysql_query($q, $this->connection);
$dbarray = mysql_fetch_array($result);
$endplan_date=$dbarray['end_plan_date'];
if($subday >0){
if($endplan_date=="0000-00-00" ){
$endplan_date = date('Y-m-d');
$new_endplan_date = date('Y-m-d',strtotime($endplan_date . "+".$subday." days"));
}else{
$new_endplan_date = date('Y-m-d',strtotime($endplan_date . "+".$subday." days"));
}
$query = mysql_query("UPDATE user SET end_plan_date='$new_endplan_date' WHERE email='$subemail'");
$recdate=gmdate('Y-m-d H:i:s');
$q = "INSERT INTO com_gest(recdate,userid,type,recvalue) VALUES ('$recdate','$userid','Plan Date','$subday')";
mysql_query($q, $this->connection);
}
if($subamt >0){
$query = mysql_query("UPDATE user SET balance=balance+".$subamt." WHERE email='$subemail'");
$recdate=gmdate('Y-m-d H:i:s');
$q = "INSERT INTO com_gest(recdate,userid,type,recvalue) VALUES '$recdate','$userid','Balance','$subamt')";
mysql_query($q, $this->connection);
}
$query = mysql_query("UPDATE user SET server='$serv' WHERE email='$subemail'");
return 0;
}
In your code u can't get directly this
$endplan_date=$dbarray['end_plan_date'];
for fetching this variable u have to use while loop like
while($dbarray = mysql_fetch_array($result);) {
$endplan_date=$dbarray['end_plan_date'];
}
There was an issue when calling this function.

how to write code in order to update stock after we sell a product

I have written following code for my sales_invoice.php
if(isset($_POST['submit1'])){
// $cat_array = $_POST['category_name'];
// $qua_array = $_POST['quantity'];
//$mrp_array = $_POST['mrp'];
//$vat_array = $_POST['vat'];
// print_r($_POST);
if(!empty($_POST['item_name']) && is_array($_POST['item_name'])){
$name_array =$_POST['item_name'];
//print_r($name_array);
for($j=0; $j< count($name_array);$j++){
$name = mysql_real_escape_string($name_array[$j]);
//echo $name;
//$n = explode('/',$name);
$sql = "select quantity from purchase_stock where item_name = '$name'";
// echo $sql;
$res = mysql_query($sql) or die(mysql_error());
$num_rows = mysql_num_rows($res);
if($num_rows <=0){
echo "<b>not in stock</b>";
exit();
}
else
continue;
}
}
$sql = "insert into material_inv set order_date='$new_date', due_date='$new_date1', dealer='".$_POST['dealer']."', customer='".$_POST['customer']."'";
// echo $sql;
$res = mysql_query($sql) or die(mysql_error());
if($res == true){
echo "sales invoice created";
}
else
{
echo "error";
}
$myid = mysql_insert_id();
$sales_id = $myid;
//display_item();
// print_r($_POST);
if (!empty($_POST['category_name']) && !empty($_POST['item_name']) && !empty($_POST['quantity']) && !empty($_POST['mrp']) && !empty($_POST['vat']) &&
is_array($_POST['category_name']) && is_array($_POST['item_name']) && is_array($_POST['quantity']) && is_array($_POST['mrp']) && is_array($_POST['vat'])){
// echo 'start';
$name_array = $_POST['item_name'];
$cat_array = $_POST['category_name'];
$qua_array = $_POST['quantity'];
$mrp_array = $_POST['mrp'];
$vat_array = $_POST['vat'];
//print_r($mrp_array);
for ($i = 0; $i < count($name_array); $i++) {
$name = mysql_real_escape_string($name_array[$i]);
$cat = mysql_real_escape_string($cat_array[$i]);
$q = mysql_real_escape_string($qua_array[$i]);
$mrp = mysql_real_escape_string($mrp_array[$i]);
//echo $mrp;
$vat = mysql_real_escape_string($vat_array[$i]);
// mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
$sql ="Insert into material_items SET category_name='$cat', item_name='$name', quantity='$q',
mrp='$mrp', vat='$vat', inv_id ='$sales_id'";
// echo $sql;
$res = mysql_query($sql) or die(mysql_error());
$sql1 = "Update stock set quantity=quantity -'$q' where item_name='$name'";
$res1 = mysql_query($sql1) or die(mysql_error());
echo "stock updated and invoice created";
}
}
}
I have first checked if item is present in purchase_stock table. (items are inserted in purchase_stock table after a purchase order is created). Then i insert in the sales table quantity which is sold. And then I write query to update stock table.
My question is do I write a insert query for stock table if no items are initially present there? Is it logically correct? Or should I keep same stock table to update quantity and items after purchase and sales transactions?
Here is an example of a stored procedure syntax
DELIMITER //
CREATE PROCEDURE GetProduct(IN param_ProductID INT)
BEGIN
SELECT *
FROM Products
WHERE ProductID = param_ProductID;
END //
DELIMITER ;
and this is how you call it from your php:
$mysqli->query("CALL GetProduct(".$param_ProductID.")");
regarding your question about inserting the the product,
you need to perform an UPSERT (insert if not exists and update if exists)
here is an example how to do it:
PHP / MySQL : Insert if doesnt exist else update
shimon :)

INSERT in a WHILE LOOP Not Inserting into Database

I have a SELECT statement, WHILE statement and an INSERT:
$result = mysqli_query($con,"SELECT winner, time, course, market, twitter_pubstatus
FROM combo
WHERE twitter_pubstatus = 0 AND market = '$win' GROUP BY winner");
while($row = mysqli_fetch_array($result))
{
$winner = $row['winner'];
$time = $row['time'];
$course = $row['course'];
$message = "$winner won the $time at $course. You are a winner! #GetIn";
$query = "INSERT INTO messageTable (MESSAGE) VALUES($message)or die(mysql_error())";
}
It runs through with no errors. There should be 12 rows that get inserted into the database. What am I doing wrong?
Try changing $query = "INSERT INTO messageTable (MESSAGE) VALUES($message)or die(mysql_error())";
to
$query = "INSERT INTO messageTable (MESSAGE) VALUES('$message')or die(mysql_error())";
Notice the single quotes in '$message'
And $query is just a string so execute the query
$result=mysqli_query($query)
And then check if query executed by doing this
if(!$result) die(mysqli_error());