Tuesday 15 July 2014

php - MySQLi, why fetch? Safest way to check query? -


For a login system I know that the username and password are correct or not, this is the code (without checking the errors etc.):

$ db = @ New MySQLi ('localhost', 'user', 'pw', 'db'); $ Sql ​​= 'Where is the user ID select? And password =? '; $ Stmt = $ db- & gt; Ready ($ sql); $ Stmt- & gt; Bind_param ('s', $ username, $ password_hash); $ Stmt- & gt; Execute () $ stmt- & gt; Bind_State ($ UserID);

Now I want to check that the result has been done, in most tutorials this has been done:

  if (! $ Stmt-> Fatch ()) {// login was wrong, what stuff} and {// login was correct, do STUFF}   

but why? It also works like this:

  if (isset ($ UserID)) {// login was correct, DO STUFF} else {// log was incorrect, do   

Or:

  If ($ UserID! = 0) {// login was correct, DO STUFF} else {// login was incorrect, STUFF   

So what is the fastest and safest way to do this?

You do not need nor "fastest" (as in slow Nothing is) nor "the safest" (as there is nothing to be unsafe).

What you need is just an sensible path

  $ stmt = $ db- & gt; Ready ($ sql); $ Stmt- & gt; Bind_param ('s', $ username, $ password_hash); $ Stmt- & gt; Execute () $ stmt- & gt; Bind_State ($ UserID); $ Stmt- & gt; Bring ();   

You now have to check the $ UserID variable and save it in session.

  if ($ UserID) {$ _SESSION ['auth'] = $ UserID; }   

As you can see, raw misskhi is very vocabulary and ugly. This is the reason why you should not use it, but some abstract layer like this

  $ db = new secure mascul (); $ Sql ​​= 'Member Selection ID where username and password =' ​​s'; If ($ UserID = $ db-> getOne ($ sql, $ username, $ password_hash)); $ _SESSION ['auth'] = $ UserID; }    

No comments:

Post a Comment