SQL Update if already exists, else insert - php

I have the following sql statement:
$sql = "INSERT INTO jos_vm_product_details (variant_id, global_variant_id,
code, size, details, color, top, price)
VALUES ('$variant_id', '$global_variant_id', '$code', '$size',
'$details', '$color', '$top', '$price')";
This is just a basic INSERT sql. Is there a way for it to Update a record if the 'variant_id' is already present. If the 'variant_id' is not already there it should Insert a new one.
Any help would be appreciated

You can check INSERT ... ON DUPLICATE KEY UPDATE

$sql = "INSERT INTO jos_vm_product_details (variant_id, global_variant_id,
code, size, details, color, top, price)
VALUES ('$variant_id', '$global_variant_id', '$code', '$size',
'$details', '$color', '$top', '$price')
ON DUPLICATE KEY UPDATE
global_variant_id = VALUES(global_variant_id),
code = VALUES(code),
size = VALUES(size),
details = VALUES(details),
color = VALUES(color),
top = VALUES(top),
price = VALUES(price)";

In MySQL you can use ON DUPLICATE KEY
INSERT INTO jos_vm_product_details (variant_id, global_variant_id,
code, size, details, color, top, price)
VALUES ('$variant_id', '$global_variant_id', '$code', '$size',
'$details', '$color', '$top', '$price')";
ON DUPLICATE KEY UPDATE `code`=VALUES(`code`);
In T-SQL (2008 an higher) you could use MERGE

Related

Storing date in MySQL

I want the date to be added to an orders table I have created, once the user proceeds to checkout. The code I currently has just prints:
"Error: Column count doesn't match value count at row 1"
Here's my code:
$sql = "INSERT INTO orders (customer_id, total, order_date) VALUES ('$name', '$total', 'DATETIME: Auto NOW()', NOW() )";
The name and total columns store but the date does not. How can I solve this?
This way:
$sql = "INSERT INTO orders (customer_id, total, order_date) VALUES ('$name', '$total', NOW())";
You want to insert data inside customer_id, total, order_date (3 rows) but you are sendig '$name', '$total', 'DATETIME: Auto NOW()', NOW(), FOUR.
Your error means that you that the number of fields does not match the number of values. That seems correct: your query tries to insert 4 values into 3 fields. You'd probably have to rewrite the query to
$sql = "INSERT INTO orders (customer_id, total, order_date) VALUES ('$name', '$total', NOW() )";
It looks like you need 3 values: customer_id, total, order_date
but you give 4 :'$name', '$total', 'DATETIME: Auto NOW()', NOW()
Maybe it should look like this:
"INSERT INTO orders (customer_id, total, order_date) VALUES ('$name', '$total', NOW() )";

If value exists in table 1 insert into table 2 mysql

For my ordering system, when an admin inserts an order i need to check if the customer he inserts for the order exists in my customer table.
Im trying something like this, but with no luck..
$sql = "IF EXISTS(SELECT * FROM customer WHERE customer_id = '$customer')
THEN insert into `order` (customer_id, product, quantity, creation_time, order_note, order_employee)
values ('$customer', '$product', '$quantity', 'now()', '$note', '$employee')";
Error: syntax error in first line.
What is wrong here?
And is this the right approach? Is there a better way?
you might want to do it "backwards" - insert if exists:
$sql = "insert into `order` (customer_id, product, quantity, creation_time, order_note, order_employee)
select '$customer', '$product', '$quantity', now(), '$note', '$employee'
from dual
where EXISTS(SELECT * FROM customer WHERE customer_id = '$customer')";
Here's a neat trick you can do:
$sql = "INSERT INTO `order`
(`customer_id`, `product`, `quantity`,
`creation_time`, `order_note`, `order_employee`)
SELECT `customer_id`, '$product', '$quantity', now(), '$note', '$employee'
FROM `customer` WHERE `customer_id`='$customer'";
Note that I'm trusting you have already properly sanitised your variables!
But this will only insert the order if the customer with that ID exists.
I think you should think your problem in another way.
Proceed with steps :
1 - I need to know if customer my customer exist?
$sql = "SELECT ID FROM customer WHERE customer_id = '$customer'";
2- I try my customer, does he exist?
If(!empty($result_cust)){
$sql = insert into `order` (customer_id, product, quantity, creation_time, order_note, order_employee)
values ('$customer', '$product', '$quantity', 'now()', '$note', '$employee')";
}
With this way your code will be more easily to understand.
Divide and Rule
They said.

Annoying query error

Note: I know MySQL is not ideal, but it's already done.
Note: I understand commited is incorrectly spelled.
QUERY ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc, cost, price, count, commited, ordered, cat, subcat, notes, rev_identifier,' at line 1
Query was INSERT INTO stock (name, desc, cost, price, count, commited, ordered, cat, subcat, notes, rev_identifier, sources, totalused, amountfailed) VALUES ('name', 'desc', '1', '1', '1', '0', '0', 'Apple', 'DEV', 'none', '1', 'none', '0', '0')
Query is written:
$db->query("INSERT INTO stock (name, desc, cost, price, count, commited, ordered, cat, subcat, notes, rev_identifier, sources, totalused, amountfailed) VALUES
('$name', '$desc', '$cost', '$price', '$count', '$commited', '$ordered', '$cat', '$subcat', '$notes', '$rev_identifier', '$sources', '$totalused', '$amountfailed')");
The $'s are...
$name = mysql_real_escape_string(strip_tags($_POST['name']));
$desc = mysql_real_escape_string(strip_tags($_POST['desc']));
$cost = mysql_real_escape_string(strip_tags($_POST['cost']));
$price = mysql_real_escape_string(strip_tags($_POST['price']));
$count = mysql_real_escape_string(strip_tags($_POST['count']));
$commited = 0;
$ordered = 0;
$cat = mysql_real_escape_string(strip_tags($_POST['cat']));
$subcat = mysql_real_escape_string(strip_tags($_POST['subcat']));
$notes = mysql_real_escape_string(strip_tags($_POST['notes']));
$rev_identifier = mysql_real_escape_string(strip_tags($_POST['rev_identifier']));
$sources = mysql_real_escape_string(strip_tags($_POST['sources']));
$totalused = 0;
$amountfailed = 0;
count is a reserved word in SQL, and you have a column called count. You'll need to put the column name in `backticks` or, better yet, rename the column.
You have used count, desc column name, it is reserved word so use backtick (“`”)` to wrap that column names
like
$db->query("INSERT INTO stock (name, `desc`, cost, price, `count`, commited, ordered, cat, subcat, notes, rev_identifier, sources, totalused, amountfailed) VALUES
('$name', '$desc', '$cost', '$price', '$count', '$commited', '$ordered', '$cat', '$subcat', '$notes', '$rev_identifier', '$sources', '$totalused', '$amountfailed')");

Using two insert statements for two different tables

I would like to use two different insert statements with two different tables such as
<?
mysql_query("INSERT INTO Customer (ID,Name,Subject, OrderDate) VALUES ('$ID', '$name', '$status', '$ODate')");
mysql_query("INSERT INTO Order (ID,Subject, Department, Status, OrderDate, Receive, Notes) VALUES ('$ID', '$status', 'Financial', 'Financial Department', '$ODate', 'NO', 'Notes')");
?>
It just works with the first table and does not work with the second table.
Can some one help solving this problem?
Thanks
You need to check for errors:
<?php
$query1 = "INSERT INTO Customer (ID,Name,Subject, OrderDate) VALUES ('$ID', '$name', '$status', '$ODate')";
if(!mysql_query($query1)) {
throw new Exception(mysql_error());
}
$query2 = "INSERT INTO Order (ID,Subject, Department, Status, OrderDate, Receive, Notes) VALUES ('$ID', '$status', 'Financial', 'Financial Department', '$ODate', 'NO', 'Notes')";
if(!mysql_query($query2)) {
throw new Exception(mysql_error());
}
I'm guessing you are getting an error because Order is a reserved word in MySQL and should be escaped accordingly:
$query2 = "INSERT INTO `Order` (ID,Subject, Department, Status, OrderDate, Receive, Notes) VALUES ('$ID', '$status', 'Financial', 'Financial Department', '$ODate', 'NO', 'Notes')";
It also seems to me like you're inserting a fixed value as a primary key - are you sure that's what you want?
As I said in the comments, you should stop using mysql_ functions completely and use MySQLi or PDO instead.
First of all thanks to DCoder who helped me to solve the problem and advised me to use PDO and MySQLi.
The problem was with the tabel name Order, when I replaced it with a new name, it works fine.
I thought the problem with using two mysql_query but it is not. The table name that I used is a reserved word in MySQL.
Thanks

Why doesn't this statement update the data in MySQL?

I'm new to MySQL. Whats wrong with this code? It doesn't update data.
"INSERT INTO highscores (name, score, maila, ip)" . "VALUES ('$name', '$score', '$maila', '$ip')" .
"ON DUPLICATE KEY UPDATE score;" . "UPDATE highscores SET (if score>'$score') {score=$score} WHERE name=$name"
This works:
"INSERT INTO highscores (name, score, maila, ip) ".
"VALUES ('$name', '$score', '$maila', '$ip') " . "
on duplicate key update score = greatest(score, $score)"
Thanks to binaryLV:
MSQL: How to overwrite entry only if new one is higher? else create new entry
When you use ON DUPLICATE KEY UPDATE, you must also specify what to update, that is, in PHP, the right query would be:
$q = "INSERT INTO highscores (name, score, maila, ip) ".
"VALUES ('$name', '$score', '$maila', '$ip') ".
"ON DUPLICATE KEY UPDATE score='$score'";

Categories