I'm trying to create a statement that inserts and updates rows in my database which changes a value in my database when values has changed while updating the row.
I'm not sure if my question is clear enough but here is my code (check the comments, this should clear things up):
$stmProducts = $db->prepare("
INSERT INTO
products
SET
identifier = :identifier,
title = :title,
price = :price,
content = :content
ON DUPLICATE KEY UPDATE
title = :title,
price = :price,
content = :content
// If any values (title, price or content) has been changed while updating:
// updated = true
");
I've tried something with CASE WHEN but that didn't work, I don't have the exact code I used but it was something like this:
updated = CASE WHEN title != :title THEN true END
I could be looking into the completely wrong direction but what's the best way to get to what I'm trying to achieve?
You can know it examining PDOStatement::rowCount(). With an insert it will return 1, while with an update will return 2.
Check the documentation
With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if
the row is inserted as a new row, and 2 if an existing row is updated.
Related
In my form, I have file type input field that is dynamically generated by add more click button.
Everything is ok, when I insert the data but i'm facing problem when I update second table which
I used for only store file type data.
I have analysed some case:
Case 1: if value exist is equal to new value then update
Case 2: if value not exist then insert data
Case 3: if value exist and greater than previous value then update the previous value and insert new data
case 4: if value exist and less than previous value then update previous and other value will be remain same(no change).
I have tried so far
$array_filename = trim($array_filename, ",");
$filename_array = explode(',', $array_filename);
$query = mysql_query("SELECT * FROMtbl_name_2WHEREjob_app_id='$editId' ");
$res = mysql_fetch_array($query);
for($i=0;$i<coun($filename_array);$i++) {
$insertQuery = "REPLACE INTOtbl_name_2(id,job_app_id,file_name) VALUES ('$res[$i]','$editId','$filename_array[$i]')";
$isInsert = mysql_query($insertQuery) or die(mysql_error());
}
mysql update if exist else insert
Should better be described as INSERT ELSE UPDATE - and that's what you can to with the ON DUPLICATE KEY UPDATE keywords and the proper unique key constraints (assuming uniqueKey column to be unique):
INSERT INTO
myTable (`id`, `uniqueKey`, `value2`) VALUES (null,"test1",17)
ON DUPLICATE KEY UPDATE
value2 = 17;
This covers your case 1 and 2: Data is inserted or updated.
For your case 3 and 4 it is unclear, what you are asking? It seems like these statements are targeting multiple tables, or what do you mean by update the previous value and insert new data?
I have this query in PHP
$id = ibase_gen_id(TABLE1_ID_GEN);
$query = "UPDATE OR INSERT INTO TABLE1(ID, TESTER_ID, LOT_ID, TEST_STEP) VALUES (.....)
MATCHING (TESTER_ID, LOT_ID, TEST_STEP)";
$processQuery = ibase_query($query);
this query works but when updating the record, the ID also updated. I want to update the record (TESTER_ID, LOT_ID, and TEST_STEP) without updating/changing its ID.
Thanks!
I'm trying to update a row or insert a new one if it exists. If there's an UPDATE I just like to update the "updated" column with the current timestamp otherwise "added" AND "updated" get the same value (timestamp)
//1385982893 is from PHP with time() cause it's needed elsewhere too
INSERT INTO table (id, code, added, updated) VALUES (236, 'abcdefghi', 1385982893, 1385982893)
ON DUPLICATE KEY UPDATE
id = values(id), code = values(code), added = values(added),updated = 1385982893
ID is the primary key. code is UNIQUE
The problem is that "added" always gets updated with the current timestamp (like updated)
You just need to to remove the added = values(added) and it won't get updated:
INSERT INTO table (id, code, added, updated) VALUES (236, 'abcdefghi', 1385982893, 1385982893)
ON DUPLICATE KEY UPDATE
id = values(id), code = values(code),updated = 1385982893
Then do not set added in Update
INSERT INTO table (id, code, added, updated) VALUES (236, 'abcdefghi', 1385982893, 1385982893)
ON DUPLICATE KEY UPDATE
id = values(id), code = values(code), updated = 1385982893
I am using jQuery draggable, when the draggable element moves I save those css values (left, top) into the database ($wpdb) using ajax... I have no problem when there is one draggable element it runs smooth... but adding onto the project I want to add multiple draggable elements and thats where I am having a problem... here is the code I am sending the data to the database...
global $wpdb;
//The data here comes from an ajax call
$_POST['x'];
$_POST['y'];
$_POST['id'];
$term_id = 100;
$name = $_POST['id'];
$slug = $_POST['x'];
$term_group = $_POST['y'];
if(isset($_POST['id'],$_POST['y'], $_POST['x'])){
print_r($_POST);
}
//Im adding into wp_terms a default table (for testing)...
$query = "INSERT INTO $wpdb->terms (term_id, name, slug, term_group) VALUES (%s, %s, %s, %s)";
//Here I insert the ajax data into the columns
$wpdb->query($wpdb->prepare($query, $term_id, $name, $slug, $term_group));
$wpdb->update("$wpdb->terms", array('slug' => $_POST['x'], 'term_group' => $_POST['y']), array('name' => $_POST['id']));
die();
This code summed up: It connects to the $wpdb then I take the data from the ajax call and store them in a variable.. I am targeting the wp_terms table... So on draggable element stop the ajax data is sent to my script and stored in the database, on update every time draggable stops I preserve that row and only update the x and y values located in slug && term_group that has the name of $_POST['id']... this updates it well, but since $term_id = 100 a static value, I cannot create a new row for an element with a new $_POST['id'].. does that make sense.. its much more simple than I think I made it out to be... I am trying to do what I am already doing but when there is a new $_POST['id'] I need to generate a $term_id = 101 dynamically it works exactally how I want if I manually give the row a term_id of 101...
Table looks like this...
Im trying to add a 101 and silly2.. then 102 silly3.. something like that, then when the last two values x & y change the 152 & 32 changes but term_id 101 stays and silly 2 stays...
The thing here is I dont want to create a new instance of silly, silly2, silly3... I want to overwrite the last two columns..
If you are running a standard Wordpress installation, the wp_terms table always has auto_increment as default for term_id, so you can just drop the static $term_id, the query now should be:
$query = "INSERT INTO $wpdb->terms (name, slug, term_group) VALUES (%s, %s, %s)";
$wpdb->query($wpdb->prepare($query, $name, $slug, $term_group));
Hope this helps.
EDIT:
Your question now is quite different than the first one. First you have to do a SELECT query to see if the row with that name exist or not, something like:
$query = "SELECT FROM $wpdb->terms WHERE name=%s"; // remember to use prepare() after this
If that row doesn't exist then you can do the INSERT like above, if that row exists then you should do an UPDATE query:
$query = "UPDATE $wpdb->terms SET slug=%s, term_group=%s WHERE name=%s";
There is also INSERT ... ON DUPLICATE KEY UPDATE solution to replace above solution but I'm not so experienced with that.
Try using auto increment in sql table definition. If you cant modify the table definition you can add one more table and link the data with it.
Edit to answer changed question.
You need to check does the value exist in the table before inserting new row.
If it exist do an update SQL query on that row. Otherwise insert new row.
$insert = $dbh->prepare('INSERT INTO tags (tag_name) VALUES (:tag)');
$insert->bindParam(':tag', $tag, PDO::PARAM_STR);
foreach($tags as $tag) {
$insert->execute();
$tag_id = $dbh->lastInsertID();
echo $tag_id."+".$photo_id."<br />";
$sql = "INSERT INTO tagrefs (tag_id, photo_id) VALUES (:tag_id,:photo_id)";
$q = $dbh->prepare($sql);
$q->execute(array(':tag_id'=>$tag_id,
':photo_id'=>$photo_id));
}
This particular piece of code inserts tags related to uploaded photos into a table called 'tags'. It links the tag_id to the photo_id in a table called 'tagrefs'. This all works fine, until I use a tag twice. Which is logical, because nothing is inserted (tags are unique, I simply want the entry in 'tagrefs' to list the photo_id for my next photo with tag_id's that already exist)
How do I make it so that my code compares the tags the user put in and compares them, or that the values of existing tags are returned and put into 'tagrefs' properly? Thank you very much in advance for your time.
If you use INSERT ... ON DUPLICATE KEY UPDATE, then lastInsertID() will return the AUTO_INCREMENT field's value of a matched row even if an UPDATE is performed instead of an insertion.
To ensure that it also works in versions of MySQL prior to v5.1.12, one can explicitly set the insertion id with MySQL's LAST_INSERT_ID() function:
INSERT INTO tags
(tag_name)
VALUES
(:tag)
ON DUPLICATE KEY UPDATE
id = LAST_INSERT_ID(id)