2
\$\begingroup\$

I have this code for updating time of login failure.The other parts of the code are stripped and simplified because my question is related to PDO.Here I have a db_config.php and a function to update time.I want to know is this a best practice for PDO connection and accessing variables in a function?

db_config.php

<?php
try 
{
  $dbh =  new PDO('mysql:host=localhost;dbname=mark1',dbusername,dbpassword);
  $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} 
catch(PDOException $e) 
{
  echo 'ERROR: ' . $e->getMessage();
} 
?>

Code for update time function.

<?php
require('db_config.php')

$login = strtolower($_POST['login']);

$sql = "SELECT * FROM members WHERE email=:email_db";
$result = $dbh->prepare($sql);
$result->bindParam(':email_db', $login);
$result->execute();
$row = $result->fetch(PDO::FETCH_ASSOC);

if($row > 0)
{
  if($row['user_failed_logins'] == 5 && $row['user_last_failed_login'] > (time() - 60) )// Blocks login attempt for 1 min.
  {
    UpdateLoginFailTime($login,$dbh);
  }
  else
  {
    //Do something...
  }

function($login,$dbh)
{
  $time = time();
  $sql_update_login_fail_fileds = "UPDATE members SET user_last_failed_login = :user_last_failed_login WHERE email = :email";
  $result_update_login_fail_fileds = $dbh->prepare($sql_update_login_fail_fileds);
  $result_update_login_fail_fileds->bindParam(':user_last_failed_login', $time);
  $result_update_login_fail_fileds->bindParam(':email', $login);
  $result_update_login_fail_fileds->execute();

  echo "You have been blocked.Please try login after 1 minute"));
}
?>
\$\endgroup\$
1
\$\begingroup\$

Please, never use procedural code-style with object oriented libraries. For php5+: this is not good code-style, please, see article about Object Oriented Programming; for php5-: this is tolerable variant(but I don't remember if php4 has had PDO).

After learning something about OOP, try to read something about MVC(Model-View-Controller) and Design Patterns(ex.: "GOF: Design Patterns")

P.S. Sorry if it seems roughly for you. But if you want to write best code - it's the only way.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Thank you for your answer.I've covered many OOP tutorials and I'll use OOP style to rewrite my codes. \$\endgroup\$ – smc Sep 24 '14 at 15:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.