Jump to content

User Authentication PDO


d239113g

Recommended Posts

Hello,  I am relativley new to php, still learning. I am trying to create a login script, using PDO so i can beable to change databases if needed in the future.

 

I have made a few login scripts before, but just using native MySQL functions,  but i am struggling trying to understand PDO.

 

What i want to do is... A user logs in with there username and password, and then if sucessful they get taken to the secure pages of the site, and an INSERT is placed in the database with the last time that user logged in. Obviously If wrong password or USername then Error message.

 

so the user table in the databse is

 

email, name , (md5) password, lastlogin.

 

Here is what i have done so far .

 

dbconnect.php

<?php

function getConnection(){
$username = 'root';
$password = '';
$dbname = 'test';
$db = new PDO( "mysql:host=localhost;dbname=$dbname", $username, $password );
    $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    return $db;
}
?>

 

i call getConnection() on pages i need to connect to the database.

 

test.php

<?php

/** require the webpage class definition file also the database connection file. */
require_once("webpage.php");
require_once("dbConnections/dbconnect.php");
try {
/* Call the PDO connection string from dbconnect.php */
$db = getConnection();

/* create a new instance of the webpage class passing the title and an array of stylesheets to the constructor */
$page = new Webpage('This is a test page', array('css/tommy.css'));

/* -------------------Header Area-------------------- */
$page->ToBody("<div id='header'>");
$page->ToBody("<h1>test</h1>");
$page->ToBody("<h3>testing</h3>");
$page->ToBody("</div>");
/* -------------------End of Header------------------- */


/* ------------------Main Body Area----------------- */
$page->ToBody("<div id='Bodytarea'>");
$page->ToBody("<div class='Body'>");

/*--------------------------Form----------------------*/
$page->ToBody("<h1>Login</h1>");
$page->ToBody("<center<form action='test2.php' method='post'>
                  <table align='left' border='0' cellspacing='0' cellpadding='3'>
                  <tr><td>Username:</td><td><input type='text' name='user' maxlength='30'></td></tr>
                  <tr><td>Password:</td><td><input type='password' name='pass' maxlength='30'></td></tr>
                  <tr><td colspan='2' align='right'><input type='submit' name='sublogin' value='Login'></td></tr>
             </table>
         </form></center>");
/*------------------------End Form--------------------*/

$page->ToBody("</div></div>");
/* -------------End of Main Body Area -------------- */

/* Call the getPage function from the webpage , which will display the head, body and footer. */
echo $page->getPage();
}
catch( PDOException $e ) {
    echo $e->getMessage();
}

?>

 

test2.php

<?php
require_once("dbConnections/dbconnect.php");

try {
/* Call connection to database function */
$db = getConnection();

/* SQL Queries ---------------------------------------- */

/*Request the post functions from the loginForm.php */
$username = $_REQUEST['user'];
$password = $_REQUEST['pass'];
$sublogin = $_REQUEST['sublogin'];

$sql="SELECT * FROM user WHERE email ='$username'
AND password='".md5($_POST['password'])."'";

$query = $db->query( $sql );

if (count($db->$query)>0) {
//Login Successful . Update the database, adding timestamp of last time member logged in.
 $db->query("UPDATE user SET lastlogin='". date("Y-m-d H:i:s",time())."' where email='".$_SESSION['username']."' and password='".$_SESSION['password']."'");

$username = $db->fetch($result);
$_SESSION['username']=$username['username'];
$_SESSION['password']=$password['password'];
//Write session to disc
session_write_close();
header("location: test2.php");
exit();
}
if(isset($_POST['sublogin'])){
   /* Check that all fields were typed in */
   if(!$_POST['user'] || !$_POST['pass']){
      die('You didn\'t fill in a required field.');
   }

   /* Checks that email is in database and password is correct */
   $md5pass = md5($_POST['pass']);
   $result = confirmUser($_POST['user'], $md5pass);

   /* Check error codes */
   if($result == 1){
      die('That username doesn\'t exist in our database.');
   }
   else if($result == 2){
      die('Incorrect password, please try again.');
   }

   /* email and password correct, register session variables */
   $_POST['user'] = $_POST['user'];
   $_SESSION['username'] = $_POST['user'];
   $_SESSION['password'] = $md5pass;
}
}
catch( PDOException $e ) {
    echo $e->getMessage();
}
?>

 

Catchable fatal error: Object of class PDOStatement could not be converted to string in C:\wamp\www\test\db\test2.php on line 20

 

Could somebody help me with this please, as i'm not getting the hang of it.

Link to comment
Share on other sites

I'm trying to understand it. Some of the examples on php.net are not very helpful i find.

 

<?php
require_once("dbConnections/dbconnect.php");

try {
/* Call connection to database function */
$db = getConnection();

/* SQL Queries ---------------------------------------- */

/*Request the post functions from the loginForm.php */
$username = $_REQUEST['user'];
$password = $_REQUEST['pass'];
$sublogin = $_REQUEST['sublogin'];

$sql= $db->prepare("SELECT * FROM user WHERE email ='$username'
AND password='".md5($_POST['password'])."'");
$sql->execute();

$result = $sql->fetchALL();

if ($db->$result()>0) {
//Login Successful . Update the database, adding timestamp of last time member logged in.
$sql2 =	 $db->prepare("UPDATE user SET lastlogin='". date("Y-m-d H:i:s",time())."' where email='".$_SESSION['username']."' and password='".$_SESSION['password']."'");

$sql2->execute();

$username = $db->fetchALL($result);
$_SESSION['username']=$username['username'];
$_SESSION['password']=$password['password'];
//Write session to disc
session_write_close();
header("location: test2.php");
exit();
}

if(isset($_POST['sublogin'])){
   /* Check that all fields were typed in */
   if(!$_POST['user'] || !$_POST['pass']){
      die('You didn\'t fill in a required field.');
   }

   /* Checks that email is in database and password is correct */
   $md5pass = md5($_POST['pass']);
   $result = confirmUser($_POST['user'], $md5pass);

   /* Check error codes */
   if($result == 1){
      die('That username doesn\'t exist in our database.');
   }
   else if($result == 2){
      die('Incorrect password, please try again.');
   }

   /* email and password correct, register session variables */
   $_POST['user'] = $_POST['user'];
   $_SESSION['username'] = $_POST['user'];
   $_SESSION['password'] = $md5pass;
}
}
catch( PDOException $e ) {
    echo $e->getMessage();
}
?>

Fatal error: Method name must be a string in C:\wamp\www\testing\db\test2.php on line 21
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.