Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select the rows affected by an update

Tags:

sql

mysql

If I have a table with this fields:

int:id_account
int:session
string:password

Now for a login statement I run this sql UPDATE command:

UPDATE tbl_name
SET session = session + 1
WHERE id_account = 17 AND password = 'apple'

Then I check if a row was affected, and if one indeed was affected I know that the password was correct.

Next what I want to do is retrieve all the info of this affected row so I'll have the rest of the fields info.
I can use a simple SELECT statement but I'm sure I'm missing something here, there must be a neater way you gurus know, and going to tell me about (:
Besides it bothered me since the first login sql statement I ever written.

Is there any performance-wise way to combine a SELECT into an UPDATE if the UPDATE did update a row?
Or am I better leaving it simple with two statements? Atomicity isn't needed, so I might better stay away from table locks for example, no?

like image 684
Poni Avatar asked Dec 01 '10 10:12

Poni


2 Answers

You should use the same WHERE statement for SELECT. It will return the modified rows, because your UPDATE did not change any columns used for lookup:

UPDATE tbl_name
SET session = session + 1
WHERE id_account = 17 AND password = 'apple';

SELECT *
FROM tbl_name
WHERE id_account = 17 AND password = 'apple';

An advice: never store passwords as plain text! Use a hash function, like this:

MD5('apple')
like image 50
Silver Light Avatar answered Oct 06 '22 02:10

Silver Light


There is ROW_COUNT() (do read about details in the docs).

Following up by SQL is ok and simple (which is always good), but it might unnecessary stress the system.

like image 36
Unreason Avatar answered Oct 06 '22 00:10

Unreason