I have a number of objects. They can be sorted into groups. When a user "drags" an object into a group, I INSERT a record into my db
INSERT INTO t1
(group_id, item_id, project_id, user_id)
VALUES
($groupID, $itemID, $projectID, $userID)
There can be multiple objects in the same group and those objects can be moved from one group to another. When I move the objects into another group, I don't need to create another record, but rather only update group_id.
EDIT:
I think I need to do something like this afterall:
table structure
t1.id
t1.group_id
t1.item_id
t1.project_id
t1.user_id
if ("SELECT id, group_id FROM t1
WHERE item_id = $itemID
AND project_id = $projectID
AND user_id = $userID")) {
// if found
UPDATE t1
SET group_id = $groupID
WHERE id = $ID
} else {
INSERT INTO t1
(group_id, item_id, project_id, user_id)
VALUES ($groupID, $itemID, $projectID, $userID)
It sounds like u should place a if statement when moving from a group to another group to update only the object being move. Say for instance if I am selecting an object from its initial(beginning) space I would add the insert statement. If I am moving an object that has already been grouped to another group I would add an update statement. Finally if I am taking an item out of all groups completely I would issue a delete statement that will remove the object from the table.
pseudo code
if object = new
{
INSERT INTO t1 (group_id, item_id, project_id, user_id)
VALUES ($groupID, $itemID, $projectID, $userID)
}
if object = group
}
UPDATE t1
SET group_id = $newgroupID
WHERE item_id = $itemID;
}
if object = banned
}
delete from t1 where item_id = $itemID
}
This sequence of code should be placed on each container that you are dragging your objects to so that it can check for the proper requirements.
You can do it in one query using insert ... on duplicate key update.
See http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html for details.
Assuming that item_id is a key, you can do
INSERT INTO t1
(group_id, item_id, project_id, user_id)
VALUES
($groupID, $itemID, $projectID, $userID)
ON DUPLICATE KEY UPDATE group_id = $groupID
I suggest you to add a surrogate primary key so you can you can identify uniquely every row. Then you can make an update like this:
UPDATE t1 SET group_id = $newgroupid WHERE id = $objectid;
Related
I need to port some data from tables on a development database into identical tables on the production database, but the production already has records with primary keys that match the dev database so I can't dump the data in with primary keysbundleRenderer.renderToStream
In this case, item_id is the primary key in the parent record, which is used to relate child records to it. Doing the insert of parent records will create a new primary key, so I need child inserts to also have the newly created primary key so that the relationship is maintained on the production databasebundleRenderer.renderToStream
my script so far:
<?php
$DB2connPROD = odbc_connect("schema","user", "pass");
$DB2connDEV = odbc_connect("schema","user", "pass");
//Get itemt records from dev
$getDevitems = "
select item_id,item_typet_id,item_identifier,expiration_timestamp
from development.itemt where item_typet_id in (2,3)
";
//$getDevitems will get records that have a primary key item_id which is used to get the records in the following select queries
foreach($getDevitems as $items){
//Get all comments
$getComments = "
select tc.item_id, tc.comment, tc.comment_type_id from development.item_commentt tc
inner join development.itemt t on tc.item_id = t.item_id
where t.item_id = {item_id_from_getDevitems}
";
$insertitem = "INSERT into production (item_identifier,expiration_timestamp)
values (item_identifier,expiration_timestamp)";
$insertComment = "INSERT into productionComment (item_id, comment, comment_type_id)
values (item_id, comment, comment_type_id)";
}
?>
So if $getDevitems returns
item_id | item_typet_id | item_identifier | expiration_timestamp
----------------------------------------------------------------------------
123 1 544 '2020-03-01 12:00:00'
I would want it to now run the comment select with 123 as the ID in the where clause:
select tc.item_id, tc.comment, tc.comment_type_id from development.item_commentt tc
inner join development.itemt t on tc.item_id = t.item_id
where t.item_id = 123
Now for my legacy parent record I have all of the parent data and all of the relational child data. so I want to insert the new parent record into the database, creating the new ID, and inserting the child record with the newly created primary key/ID. So for the new parent record I would do:
$insertitem = "INSERT into production (item_identifier,expiration_timestamp)
values (544,'2020-03-01 12:00:00')";
Let's say that creates the new record with item_id = 43409. I want my comment insert to be:
$insertComment = "INSERT into productionComment (item_id, comment, comment_type_id)
values (43409, comment, comment_type_id)";
Bottom LIne: I need to take relational data (all based on item_id) from a development database, and insert these into a new database which creates a new primary key but I need to keep the relationship.
How can I properly finish this to do what I need and make sure I maintain the full relationship for each originally selected item?
Given that your inserts are:
$insertitem = "INSERT into production (item_identifier,expiration_timestamp)
values (item_identifier,expiration_timestamp)";
$insertComment = "INSERT into productionComment (item_id, comment, comment_type_id)
values (item_id, comment, comment_type_id)";
It looks like you are using an identity column for item_id. You can retrieve the most recent generated identity value using the IDENTITY_VAL_LOCAL() function so the second insert should be:
$insertComment = "INSERT into productionComment (item_id, comment, comment_type_id)
values (IDENTITY_VAL_LOCAL(), comment, comment_type_id)";
I cannot help with PHP but with DB2 for IBMi you have different solutions :
If i understand it correctly item_id is a GENERATED ALWAYS as IDENTITY column
You can get newly created item_id using
select item_id from final table (
INSERT into production (item_identifier,expiration_timestamp)
values (544,'2020-03-01 12:00:00')
)
Or you can force value of item_id with dev value or your own increment
INSERT into production (idtem_id, item_identifier,expiration_timestamp)
values (<your value>, 544,'2020-03-01 12:00:00')
OVERRIDING SYSTEM VALUE
In this case you will have to set next value for item_id by issueing
alter table production alter column item_id restart with <restart value>
I have this stored procedure that has 2 parameters, the first one is the cartId(which is the IN) and I have the newOrderId(which is the OUT). Now,
I know that the inCartId is the cart id which will come from the form or whatever means the cart is been access but I don't understand the OUT
newOrderId since that is what MySQL will return.
Now, in the PHP calling this Stored procedure, it will look like this.
$sql = 'CALL create_order(:cart_id, "What will be here")// The cart_id is what PHP will pass to MySQL, but what will be passed
to the 2nd argument since PHP does not know before hand what MySQL will return.
CREATE PROCEDURE create_order(
IN inCartId int,
OUT newOrderId int
)
BEGIN
-- Insert a new record into orders and obtain the new order ID
INSERT INTO orders (created_on) VALUES (NOW());
-- Obtain the new Order ID
SELECT LAST_INSERT_ID() INTO newOrderId;
-- Insert order details in order_detail table
INSERT INTO order_detail (
order_id, product_id, attributes, product_name, quantity, unit_cost
)
SELECT
orderId,
p.id,
sc.attributes,
p.name,
sc.quantity,
COALESCE( NULLIF( p.discounted_price, 0 ), p.price ) AS unit_cost
FROM
shopping_cart sc
INNER JOIN products p ON sc.product_id = p.id
WHERE
sc.cart_id = inCartId
AND
sc.buy_now;
-- Save the order's total amount
UPDATE
orders
SET
total_amount = (
SELECT
SUM( unit_cost * quantity )
FROM
order_detail
WHERE
order_id = orderId
)
WHERE
id = orderId;
-- Clear the shopping cart
CALL shopping_cart_empty(inCartId);
END```
Have been able to solve it. And this is how I did it.
CREATE PROCEDURE `shopping_cart_create_order2`(IN `inCartId` INT(11), OUT `newOrderId` INT(11)) BEGIN
DECLARE newOrder int;
-- Insert a new record into orders and obtain the new order ID
INSERT INTO orders (created_on) VALUES (NOW());
-- Obtain the new Order ID
SELECT LAST_INSERT_ID() INTO newOrder;
-- Insert order details in order_detail table
INSERT INTO order_detail (
order_id, product_id, attributes, product_name, quantity, unit_cost
)
SELECT
newOrder,
p.id,
sc.attributes,
p.name,
sc.quantity,
COALESCE( NULLIF( p.discounted_price, 0 ), p.price ) AS unit_cost
FROM
shopping_cart sc
INNER JOIN products p ON sc.product_id = p.id
WHERE
sc.cart_id = inCartId
AND
sc.buy_now;
-- Save the order's total amount
UPDATE
orders
SET
total_amount = (
SELECT
SUM( unit_cost * quantity )
FROM
order_detail
WHERE
order_id = newOrder
)
WHERE
id = newOrder;
-- Clear the shopping cart
CALL shopping_cart_empty(inCartId);
SET newOrder = newOrderId;
END
At PHP level// Probably at the Model/Entity level
First, we need to execute the
shopping_cart_create_order2()
stored procedure. Which might probably be in a function.
Second, to get the last order id, we need to query it from the variable
#oid
. It is important that we must call the method
closeCursor()
of the PDOStatement object in order to execute the next SQL statement.
function query($pdo, $sql, $parameters = []){
$query = $pdo->prepare($sql);
$query->execute($parameters);
return $query;
}
function create_order($pdo, $cart_id){
// Binding the parameters
$parameters = [':cart_id' => $cart_id];
// calling stored procedure command
$sql = 'CALL shopping_cart_create_order2(:cart_id)';
// prepare for execution of the stored procedure, pass value to the command
and execute the Stored Procedure
$query = query($pdo, $sql, $parameters);
// Then close Cursor. It is important for you to close it.
$query->closeCursor();
// execute the second query to get last insert id
$row = $pdo->query("SELECT #oid AS oid")->fetch();
return $row;
}
For more info, see enter link description here
I hope am able to help someone out there who might probably fall into what I passed through.
I have 2 tables, each with 3 columns
Table1 has a columns, id, code and name
Table2 has a columns, id, name and table1id
When new records are created in Table2 the column table1id needs to be filled out with the id Table1 has for that name.
The query must look at the last id created in Table2 and match the Table2 name column with the name in Table1 and then append the id associated with the name to Table2.
How can this be done correctly? The following is the PDO structure I have:
$last_id = $conn->lastInsertId();
$stmt = $conn->prepare('UPDATE `Table2` SET `table1id` = :last_id_0) WHERE `id` = :last_id');
$stmt->execute([
]);
The variable :table1id should be based on the last created record in Table2 but I am unsure with how to continue from here.
This is a visual representation of the two tables described:
UPDATE:
Last inserted id is assigned to the variable $last_id like this:
$stmt = $conn->prepare( ' INSERT INTO `Table2` (`name`)
VALUES (:name ) ' );
$stmt->execute([
'name' => $_POST['name']
])
$last_id = $conn->lastInsertId();
I think I know what you want. I assume table1 has already existed for a long time, and all you do is insert a row into table2. You can use an INSERT INTO SELECT like this:
$stmt = $conn->prepare('INSERT INTO `Table2` (`name`, `table1id`)
SELECT `name`, `id`
FROM `table1`
WHERE `table1`.`name` = :name');
$stmt->execute(['name' => $_POST['name']]);
This query inserts a new row into table2 using the selected name and id from table1. The selected record in table1 is the one with the matching name.
Please note that this will only work if the names in table1 are unique.
if you need to change table2.table1id according to table1.name.
$last_id = $conn->lastInsertId();
$stmt = $conn->prepare('UPDATE Table2
INNER JOIN table1 ON Table1.name = Table2.name
SET Table2.table1id = :id
WHERE Table1.name = :name');
$stmt->execute(['id'=>$last_id , 'name' => $_POST['name']])
Why not to write a query which is just verbatim your requirement?
look up records in one table
$stmt = $conn->prepare('SELECT id from table1 where name=?');
$stmt->execute([$_POST['name']]);
$row = $stmt->fetch();
append data to another
$stmt = $conn->prepare('INSERT INTO `Table2` (`table1id`) VALUES (:t1id)');
$stmt->execute(['t1id' => $row['id']);
Note that it's a very bad idea to duplicate data in the tables, so it's best to keep the name only in table1. You can always have it for table2 using JOIN.
I have used bulk update to sync datas between two tables as below
$sqlProc="
UPDATE cards
SET cards.card_no = t2.card_number,
cards.expiry_date=t2.expiry_date OUTPUT INSERTED.Id AS 'updated_id'
FROM cards
INNER JOIN card_temp t2 ON (cards.account_no = t2.account_number
AND cards.customer_name=t2.customer_name)
WHERE cards.is_disabled='N'";
debug($this->Request->query($sqlProc));
Above query will also return Primary key of updated records usingOUTPUT INSERTED.Id AS 'updated_id' in sql server editor but when i debug the sql
debug($this->Request->query($sqlProc));
Then it return true for successful query and false for unsuccessful query.
Is there any idea to fetch updated_id to array , so that i can use those ids to another table
Well , I figured out finally . I created one intermediate table did the following
//inserted into temp_id (bridge table)
$sqlProc="insert into temp_id select * FROM (update cards
set cards.card_no = t2.card_number,cards.expiry_date=t2.expiry_date
OUTPUT INSERTED.Id AS 'updated_id'
from cards
inner join card_temp t2
on (cards.account_no = t2.account_number and cards.customer_name=t2.customer_name)
where cards.is_disabled='N'
) AS t";
$this->Request->query($sqlProc);
//fetch from intermediate table
$sqlSel="SELECT * FROM temp_id";
$arr=$this->Request->query($sqlSel);
//this array will fetch all updated id's
debug($arr);
$sqlDel="DELETE FROM temp_id";
$this->Request->query($sqlDel);
I am having a problem locating comments for a given user with the following table structure:
usertable (id, userid, name)
comments (id, commentname, date)
Note: usertable.id is not the same as comments.id, and they are both autoincrement
How should I go about updating these tables to fix this problem?
Update
Is this code good for all users get their own votes when someone voted as thilo savage told me ?
$sth = thumbsup::db()->prepare(
'INSERT INTO'
.thumbsup::config('database_table_prefix')
.'votes_users(vid, userid) VALUES (?,?)');
$sth->execute(array($this->vid, $userid));
You've got two options:
Add a 'uid' column to the comments table which references the usertable's 'id' column. That way, you have a way to keep track of which comments belong to which users.
Create a table 'user_comment' with the columns 'uid' and 'cid'. This option leaves the two existing tables as they are, and the 'user_comment' table is responsible for keeping track of which comments belong to which users.
EDIT: Rewritten to use many-to-many relationship because current tables can't be altered.
Create a new table called comments_users with these fields:
cuid (primary key and auto increment) | cid | uid
Then get all of a user's comments with this code:
$user_id = '1234';
// get all the user's comment ids from comments_users table
$find = mysql_query("SELECT `cid` FROM `comments_users` WHERE `uid` = '".$user_id."'");
// generate a query that grabs all those comments
$load = "SELECT * FROM `comments` WHERE ";
while ($row = mysql_fetch_array($find) {
$load .= "`id` = '".$row['cid']."' OR ";
}
// shop off the last OR
$load = substr($load,0,-4);
// put all the user's comments into comments array
$q = mysql_query($load);
while ($comment = mysql_fetch_array($q)) {
$comments[] = $comment
}
print_r($comments);
As far as inserting goes, you'll insert comments into the comments table like you normally would, but then you'd ALSO insert a row into comments_users table filling in the appropriate cid and uid for that comment