I'm trying to run an INSERT query into a table with 3 columns. The first column is where I'm having the issue.
It is called COMM_CODE with VARCHAR value of 10 length, and is the primary key, ALLOW NULL is unchecked.
The values for COMM_CODE look like this:
COMM_CODE
c20188
c20189
c20190
// and so on
What I would like to do, is when a new record is inserted, to basically add 1 to the most recent record.
Therefore, the most recent record is:
c20190
So when I add a new record, the COMM_CODE for the new record will be:
c20191
I tried this:
INSERT INTO table_c
(COMM_CODE, COMM_DESC, DATE)
VALUES
(''+1, 'VIDEO GAMES', NOW());
But that just adds a number 1 to that column.
How can I make this happen?
Here the solution for your query :
To generate the new code I'hv created get_new_code function in mysql. I hope you know how funcions work in mysql.
CREATE FUNCTION `get_new_code`() RETURNS varchar(11)
BEGIN
Declare var_code VARCHAR(11);
SELECT max(`COMM_CODE`) INTO var_code FROM table_c;
RETURN (CONCAT('c',(convert(substr(var_code,2,length(var_code)), SIGNED INTEGER)+1)));
END
Just to verify your logic you can use :
select get_new_code();
So that you will get the clear picture.
Call this get_new_code function in insert query like this :
INSERT INTO
`table_c`(`COMM_CODE`, `COMM_DESC`, `COMM_DATE`)
VALUES
(get_new_code(),'Description text',NOW());
This should solve your problem. :)
Related
I want to insert new record in database if not already present. I know I can do it if I make that column unique but cant do this as there are several redundant records already present . So i wish any new record I insert should only be inserted if not already present.
Sample table for reference
id name
1 a
2 b
3 c
Before inserting do a select query:
Select id from tablename where name = 'a' limit 1;
Then check, if the result has rows. If it does not have rows execute the insert statement.
INSERT IGNORE INTO... You can find more info on already accepted answer on another question.
I will use pseudo-code to explain .
Use a select query with a WHERE that gonna select only value/values that is/are equal to the value/values of the input type .
You will have to store the values in variables , one variable for the input type and one variable to store the value for the select query.
Before that don't forget to store variables because if you do a search it will read the value but not gonna store it and the second reason is it's gonna help you for the if and else if .
Also i will recommend you to see POST method and REQUEST method and logic operators ( ex: && , || , etc ... )
You should use a if and a else if .
The if could be:
if variable1 = variable 2
echo "Data already exist" ;
end of the if
the else if could be :
Insert query
end of the else
You should echo the value that you get from the select query just to be sure for your test.
I am refering to this post. I am stuck with a problem I can't resolve. I try to insert multiple rows with a php script into a MySQL database. I don't succeed in updating the whole thing using ON DUPLICATE KEY UPDATE and using a WHERE condition (at the end of the code below) I would like to use to update only an entry has been modified recently:
// for information (used in a foreach loop):
$args[] = '("'.$row['lastname'].'", '.$row['phone'].', "'.$row['lastModification'].'")';
// then:
$stringImplode = implode(',', $args);
// Where I am stuck - WHERE statement:
$sql = $mysqli->query('INSERT INTO table_name '. (lastname, phone, timestamp) .' VALUES '.$stringImplode .'ON DUPLICATE KEY UPDATE lastname=VALUES(lastname), phone=VALUES(phone) WHERE timestamp > VALUES(lastModification);
Everything works fine except I cannot set any WHERE condition at this point that involves multiples entries. Maybe the WHERE statement in this case is not intended to refer to a condition in this statement.
I was told to try with a database procedure using a JOIN statement and a temporary table with first all my entries and then querying some conditions. But I have to admit I don't understand very well how I could leverage such a table to update an other table.
Is there an easy and lovely way to use a "CASE WHEN" or an "IF" statement in this case?
Would something like
INSERT INTO ... ON KEY DUPLICATE UPDATE lastname = VALUES(lastname), phone = VALUES(phone)
CASE WHEN (timestamp > VALUES(lastModification)) THEN do nothing ...
or
...ON KEY DUPLICATE UPDATE... IF (timestamp > VALUES(lastModification)) ...
If anyone could help me, I would be very grateful.
EDIT: Since I will have many variables, could it be used in this way:
INSERT INTO ... ON KEY DUPLICATE UPDATE
IF(timestamp > VALUES(timestamp),
(
name = VALUES(name),
number = VALUES(number),
timestamp = VALUES(timestamp)
....many other variables
),
(
name = name,
number = number,
timestamp = timestamp
....many other variables)
)
You can use simple IF function in value like this:
INSERT INTO ... ON KEY DUPLICATE UPDATE
name = VALUES(name),
number = VALUES(number),
timestamp = IF(timestamp > VALUES(timestamp), VALUES(timestamp), timestamp)
If condition is not met, it will update timestamp with the same timestamp which already exists. It does not matter, because update to same values is optimized before it is even executed, so MySQL will not make real update. You should not afraid of some performance penalty.
EDIT:
IF works likes this:
IF(condition, returned when true, returned when false)
Maybe you need to switch those two arguments to fit your condition like you want.
I have been trying to get the following SQL to work however it seems to skip the insert function. Essentially updating should take priority as most of the time it should fire.
UPDATE `teams-tasks`
SET status=(:s), name=(:n), description=(:d), importance=(:i), applies=(:a)
WHERE teamId =(:t) AND date=(:da) AND playerId =(:p) AND creatorId =(:c);
IF (SELECT ROW_COUNT() = 0);
INSERT INTO `teams-tasks`
( status, date, creatorId, teamId, playerId, name, description, importance, applies )
VALUES
( (:s), (:da), (:c), (:t), (:p), (:n), (:d), (:i), (:a) ))
what am i doing wrong?
i am using php pdo for my database connection if it matters
thanks
User replace into query which makes sure if the row exists it will update the data, if row does not exists it will insert the date.
to check the duplicate entry it compares the primary key internally
e.g.
REPLACE INTO table_name(column_name1,column_name2,…)
VALUES(value1,value2,…)
e.g.
REPLACE INTO offices(officecode,city)
VALUES(8,'San Jose')
Thanks
Amit
You should use INSERT ... ON DUPLICATE KEY UPDATE
For example
INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE
Timestamp=VALUES(Timestamp)
Here is a part of my php code:
foreach ($value->ahkam as $k => $v){
echo $v->id."\n";
//Save into db one hokm
$addHokm = "INSERT INTO qm_hokm (hokm_id, type, tooltip, line, x1, y1, x2, y2, radius, XOrigin, YOrigin, page_id)
VALUES ($v->id,$v->type,'tooltip',0,$v->x1,$v->y1,$v->x2,$v->y2,$v->r,$v->XOrigin,$v->YOrigin,$pageNumber)";
if(!mysqli_query($con, $addHokm))
echo "Failed to insert into db...".$v->id."\n";
}
In fact, I am fetching a json structure sent by an ajax request from a client.
I have many values in $value->ahkam but the problem is that only the first query is run and the others give me the error msg. Any help plz
UPDATE:
the result of echo is:
0
1
Failed to insert into db...1
2
Failed to insert into db...2
As you see, the hokm number 0 is added but not the others, I need to mention also that $pageNumer is a foeign key
The problem is in your foreign key, it must not be unique. Like that, you can add multiple entries for one page_id. I hope it is the correct answer:)
Based on your comments, it appears that your query is inserting a duplicate value for the page_id value, which appears to be set as a field that cannot have duplicate values. According to your query, you're using $pageNumber for that field, but I don't see it changing in your loop. You either need to get rid of the constraint preventing you from using the same value or make sure that $pageNumber has a value that isn't being used already.
So I have an import/export module for OpenCart, but it's wiping the entire product option table before inserting new data...
I need to develop support for the 3rd party product options module I have, but in the meantime--I figure I'd just stop it from deleting an important column in my product options table.
In the product_option_value table, I have 'product_option,' 'product_id,' 'quantity' etc., and there's one column named 'info' that I want to NOT wipe. The method is below:
function storeOptionsIntoDatabase( &$database, &$options )
{
// find the default language id
$languageId = $this->getDefaultLanguageId($database);
// start transaction, remove options
$sql = "START TRANSACTION;\n";
$sql .= "DELETE FROM `".DB_PREFIX."product_option`;\n";
$sql .= "DELETE FROM `".DB_PREFIX."product_option_description` WHERE language_id=$languageId;\n";
$sql .= "DELETE FROM `".DB_PREFIX."product_option_value`;\n";
$sql .= "DELETE FROM `".DB_PREFIX."product_option_value_description` WHERE language_id=$languageId;\n";
$this->import( $database, $sql );
...more code...
}
I'm not that familiar with MySQL, but I want something to the effect of:
$sql .= "DELETE FROM `".DB_PREFIX."product_option_value` WHERE column != 'info';\n";
Thanks!
Edit:
I tried Michael's suggestion to use UPDATE and explicitly setting them all to NULL... but that returned this error:
Error: Duplicate entry '0' for key 1
Error No: 1062 UPDATE
oc_product_option_value SET
product_option_value_id=NULL,
product_option_id=NULL,
product_id=NULL, quantity=NULL,
subtract=NULL, price=NULL,
prefix=NULL, sort_order=NULL,
weight=NULL, sku=NULL, image=NULL
I tried taking out the primary key:
$sql .= "UPDATE
".DB_PREFIX."product_option_value
SET product_option_id=NULL,
product_id=NULL, quantity=NULL,
subtract=NULL, price=NULL,
prefix=NULL, sort_order=NULL,
weight=NULL;\n";
but I get:
Error: Duplicate entry '1' for key 1
Error No: 1062 INSERT INTO
`oc_product....
Edit:
Okay, so I removed the 'primary_key' field from the INSERT... and I got no error messages from the upload. But when I view a product that product options, I get this message the top of my page:
Notice: Undefined index: name in
/httpdocs/ocart/catalog/model/catalog/product.php
on line 418Notice: Undefined index:
name in
/httpdocs/ocart/catalog/model/catalog/product.php
on line 418Notic.... it repeats
Make sure I understand: You want to clear values from all columns in the table product_option_value except for the column info ? If that's what you want, then the following may work. Please don't run it before we're clear on what you're trying to do!
DELETE FROM syntax implies deleting from a table name, not a column name. What you'll need to do instead is to UPDATE your rows to set all columns except the one you intend to keep to be either NULL or empty or their default value.
Don't forget to add a WHERE condition if you need to keep some rows as they are without modifying them! Without a WHERE, this query will NULL out all columns specified in the whole table.
UPDATE product_option_value
SET
product_option = NULL,
product_id = NULL,
quantity = NULL,
etc...
WHERE (some where condition if you need one)
I'm adding a second answer, taking a completely different approach which avoids SQL problems.
Export your table as a comma-separated text file. You can do this with phpmyadmin, or MySQL Workbench.
Open your CSV in a spreadsheet
Clear out the columns you want to clear out.
Save as a new CSV
Import the CSV back into your database using phpmyadmin, Workbench, or the LOAD DATA LOCAL INFILE syntax.