cgwebprojects
cgwebprojects

Reputation: 3482

Is it possible to UPDATE then INSERT in mysql?

Is it possible to UPDATE and then INSERT where row exists in mysql? I have this query,

$q = $dbc -> prepare("UPDATE accounts SET lifeforce = maxLifeforce, inHospital = 0 WHERE hospitalTime <= NOW() AND inHospital = 1");
$q -> execute();

How can I either get the primary key into an associative array to then do an insert for each item in the array, or do an UPDATE AND INSERT?

Or does it involve doing a SELECT to get all that match criteria, then UPDATE then INSERT using array from the select? This seems rather a long way to do it?

Basically I need to INSERT onto another table using the same primary keys that get updated.

Upvotes: 1

Views: 568

Answers (3)

ruakh
ruakh

Reputation: 183612

Or does it involve doing a SELECT to get all that match criteria, then UPDATE then INSERT using array from the select?

Yes, sorry, that's the main way.

Another approach is to add a column called (say) last_updated, that you set whenever you update the column. You can then use that column in a query that drives your insert. That would have other advantages — I find last_updated columns to be useful for many things — but it's overkill if this is the only thing you'd ever use it for.


Edited to add: Another option, which just occurred to me, is to add a trigger to your accounts table, that will perform the insert you need. That's qualitatively different — it causes the insertion to be a property of accounts, rather than a matter of application logic — but maybe that's what you want? Even the most extreme partisans of the "put-all-constraints-in-the-database-so-application-logic-never-introduces-inconsistency" camp are usually cautious about triggers — they're really not a good way to implement application logic, because it hides that logic somewhere that no-one will think to look for it. But if the table you're inserting into is some sort of account_history table that will keep track of all changes to account, then it might be the way to go.

Upvotes: 3

Ayman Safadi
Ayman Safadi

Reputation: 11552

You can use the mysqli_last_id function: http://php.net/manual/en/mysqli.insert-id.php

Also, when running consecutive queries like that, I'd recommend using transactions: http://www.techrepublic.com/article/implement-mysql-based-transactions-with-a-new-set-of-php-extensions/6085922

Upvotes: 0

Nanne
Nanne

Reputation: 64439

You can use a multiple table update as written in the manual: http://dev.mysql.com/doc/refman/5.0/en/update.html

If the second table needs an insert, you probably would have to do it manually.

Upvotes: 0

Related Questions