简体   繁体   中英

PHP mysql faster way to select statement for later update?

I have the following code:

$result = mysqli_prepare($con, "select pass from signin where domain = ? and username = ? for update");
//Check if record is available
//Do some checking here that pass is correct
//Then I need a new hash for the password so I use (after making the new hash)
$resultnew = mysqli_prepare($con, "update signin set pass = ? where domain = ? and username = ?");

So everything is working fine here!

But what I don't like is that there is wasted time when the update statement has to look for the record with the domain and password again as I already have the record from the first select statement.

Is there a way to directly update the pass from the first select statement after doing the checking? In short is there something like this or should I stick with what I am doing:

password = select pass from signin where domain = ? and username = ?;
//checking and making new hash
set password = $newhash

You should use an unique ID for each row of your database. This should be an index, preferrably with auto-increment on. An example of such a table:

CREATE TABLE IF NOT EXISTS `my_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
   <other columns>
   PRIMARY KEY (`ID`),
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

If you return the ID along with the password you can use the ID to directly select the correct row for your UPDATE command.

UPDATE signin 
SET pass = ? 
WHERE id = ? 

Since ID is your primary index this will be very quick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM