Hi,
I was trying to develop a login script using OO php.But I found it is not directing to the menu page even with the correct login details ,instead it is redirect to the login page.Even it is not giving any error messages.Can anybody tell me whats wrong there..Im here posting the 2 files.Thank you...

database.php

<?php


class database{
     
    function __construct() {   

     $db_name = 'Lakkam';        
     $db_host = 'localhost';    
     $db_user = 'root';
     $db_password = '';

        $con = mysql_connect ($db_host,$db_user,$db_password)
           or die("Could not connect to MySQL server. Please try again.");
           mysql_select_db($db_name,$con)
           or die("Could not connect to the database. Please try again");      

    }

    function login($uname,$pass)
	{ // after creating the database object you have to pass username & password
	
			// username and password sent from form
			$myusername=$_POST['username'];
			$mypassword=md5($_POST['password']);
			
			// To protect MySQL injection 
			$myusername = stripslashes($myusername);
			$mypassword = stripslashes($mypassword);
			$myusername = mysql_real_escape_string($myusername);
			$mypassword = mysql_real_escape_string($mypassword);
			   
		   $sql=sprintf("SELECT user_id,user_name,user_password FROM 'tbl_admin' WHERE user_name = '$myusername' AND user_password ='mypassword'");
		   $query = mysql_query($sql);
           
            if(mysql_num_rows($query) == 1) // checks if a user name with that password exsists
            {
                    $row = mysql_fetch_assoc($query); // Put it to an associative array
                    session_start();
                    $_SESSION['user_id'] = $row['user_id'];  
                    $_SESSION['logged_in'] = "ok";
                    header("Location: menu.php");
                    return true;       
            }
            else 
	   {   
		    header("Location: login.php");    
                    return false;   
            }
   
    }

}


?>

login.php

<?php

include_once ('database.php'); // This is the location of your database class in your server
    $con= new database(); // create the database object
   
      if(isset($_POST['Submit'])){   // Check if the form is actually submitted
        if($_POST['username']!='' && $_POST['password']!='')
        {
           
            if($con->login($_POST['username'],$_POST['password'])){  //check the username & password
            }else{
            $error = 'Incorrect Login Details ...Try again later!<br>';   
            }
           
        }
        else {
            $error = 'Username Or Password Field is Empty..Please Check again!<br>';
        }
    }

?>

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Lakkam Trade Center</title>
<meta name="keywords" content="" />
<meta name="description" content="" />

</head>
<body>
<div id="Layer1"><img src="images/login.jpg" alt="" width="149" height="132" /></div>

<p>&nbsp;</p>
<div align="center" class="style1" id="Layer2">Administrator Login </div>
<div id="Layer3">
<form id="form1" name="form1" method="post" >
  <p>Username
    <input type="text" name="username" />
  </p>
  <p>&nbsp;</p>
  <p>Password
    &nbsp;<input type="password" name="password" />  
    </p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>
    <input type="submit" name="Submit" value="Login" />
	<input type="reset" name="Reset" value="Reset" />
	 <?php if(isset($error)){ echo "<span class=\"style6\">$error</span>";} //display errors?> 
  </p>
</div>
<div id="main">

<div id="header"></div>


</body>
</html>

Try with below code.

database.php

<?php


class database{
     
    function __construct() {   

     $db_name = 'Lakkam';        
     $db_host = 'localhost';    
     $db_user = 'root';
     $db_password = '';

        $con = mysql_connect ($db_host,$db_user,$db_password)
           or die("Could not connect to MySQL server. Please try again.");
           mysql_select_db($db_name,$con)
           or die("Could not connect to the database. Please try again");      

    }

    function login($uname,$pass)
	{ // after creating the database object you have to pass username & password
	
			// username and password sent from form
			$myusername=$_POST['username'];
			$mypassword=md5($_POST['password']);
			
			// To protect MySQL injection 
			$myusername = stripslashes($myusername);
			$mypassword = stripslashes($mypassword);
			$myusername = mysql_real_escape_string($myusername);
			$mypassword = mysql_real_escape_string($mypassword);
			   
		   $sql=sprintf("SELECT user_id,user_name,user_password FROM 'tbl_admin' WHERE user_name = '$myusername' AND user_password ='mypassword'");
		   $query = mysql_query($sql);
           
            if(mysql_num_rows($query) == 1) // checks if a user name with that password exsists
            {
                    $row = mysql_fetch_assoc($query); // Put it to an associative array                    
                    return $row['user_id'];                      
            }
            else 
	   		{  
				return false;   
            }
   
    }

}


?>

Login.php

<?php session_start();

include_once ('database.php'); // This is the location of your database class in your server
    $con= new database(); // create the database object
   
      if(isset($_POST['Submit'])){   // Check if the form is actually submitted
        if($_POST['username']!='' && $_POST['password']!='')
        {
            $output = $con->login($_POST['username'],$_POST['password']);
            if($output)
			{  //check the username & password
				
				$_SESSION['user_id'] = $output;  
                $_SESSION['logged_in'] = "ok";
				
				header("Location: menu.php");
				exit;					
            }
			else
			{
            	$error = 'Incorrect Login Details ...Try again later!<br>';   
            }
           
        }
        else
		{
            $error = 'Username Or Password Field is Empty..Please Check again!<br>';
        }
    }

?>

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Lakkam Trade Center</title>
<meta name="keywords" content="" />
<meta name="description" content="" />

</head>
<body>
<div id="Layer1"><img src="images/login.jpg" alt="" width="149" height="132" /></div>

<p>&nbsp;</p>
<div align="center" class="style1" id="Layer2">Administrator Login </div>
<div id="Layer3">
<form id="form1" name="form1" method="post" >
  <p>Username
    <input type="text" name="username" />
  </p>
  <p>&nbsp;</p>
  <p>Password
    &nbsp;<input type="password" name="password" />  
    </p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>
    <input type="submit" name="Submit" value="Login" />
	<input type="reset" name="Reset" value="Reset" />
	 <?php if(isset($error)){ echo "<span class=\"style6\">$error</span>";} //display errors?> 
  </p>
</div>
<div id="main">

<div id="header"></div>


</body>
</html>

at line 36 in database.pbp you might try:

if($query)

instead of

if(mysql_num_rows($query) == 1)

because I've had experiences with mysql_query sending me more rows than I thought I would get. Also mysql_query will return FALSE with no result set so that would work for no user. Side note: I am really curious about mysqli which looks to be an improved extension for mysql.

@vibhadevit


It gives me the following warning..
"Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\wamp\www\Lakkam\admin\database.php on line 26"

And also it redirect to login.php and print the error message "Incorrect Login Details ...Try again later!" with the correct login details.:(

@ektron

yeah it removes the warning..but still gives the error message "Incorrect Login Details ...Try again later!" for correct login details..Why is that?

do one thing.
export your db table and post it here.
i will check it local and will post exact code.

I dont know how to attach it here..Im just posting...By the way Thanks alot for helping me...:)

-- phpMyAdmin SQL Dump
-- version 3.2.0.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Aug 21, 2010 at 06:26 AM
-- Server version: 5.1.36
-- PHP Version: 5.3.0

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `lakkam`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_admin`
--

CREATE TABLE IF NOT EXISTS `tbl_admin` (
`user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_name` varchar(20) NOT NULL DEFAULT '',
`user_password` varchar(32) NOT NULL DEFAULT '',
`user_regdate` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`user_last_login` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `tbl_admin`
--

INSERT INTO `tbl_admin` (`user_id`, `user_name`, `user_password`, `user_regdate`, `user_last_login`) VALUES
(2, 'admin2', '21232f297a57a5a743894a0e4a801fc3', '2010-06-03 19:10:56', '2010-06-03 19:10:56');

@sami.asanga obviously...I see that in your login function in your database class you have two parameters $uname and $pass. Then you set both $myusername and $mypassword to the $_POST variables instead of using your function input parameters. Then in the html form code in login.php you have no action="example.php" set for your form. Who knows where your form variables are posting to. Try this: set <form action="login.php" name="etc....> and change $myusername=$uname and $mypassword=$pass. I think your form's data is floating off somewhere. Also try getting rid of the right curly braces on line 15 and 19 in login.php, and set your first ELSE to an ELSEIF. Within that same IF construct try setting $error to something affirmative right under IF before any of your ELSE's. Hopefully this bears some fruit.

There was minor mistakes.
I have removed it.
Check with below code.
Surely it will work.

database.php

<?php


class database{
     
    function __construct() {   

     $db_name = 'Lakkam';        
     $db_host = 'localhost';    
     $db_user = 'root';
     $db_password = '';

        $con = mysql_connect ($db_host,$db_user,$db_password)
           or die("Could not connect to MySQL server. Please try again.");
           mysql_select_db($db_name,$con)
           or die("Could not connect to the database. Please try again");      

    }

    function login($uname,$pass)
	{ // after creating the database object you have to pass username & password
	
			// username and password sent from form
			$myusername=$_POST['username'];
			$mypassword=md5($_POST['password']);
			
			// To protect MySQL injection 
			$myusername = stripslashes($myusername);
			$mypassword = stripslashes($mypassword);
			$myusername = mysql_real_escape_string($myusername);
			$mypassword = mysql_real_escape_string($mypassword);
			   
		   $sql="SELECT user_id,user_name,user_password FROM tbl_admin WHERE user_name = '$myusername' AND user_password ='$mypassword'";
		   $query = mysql_query($sql);
           
            if(mysql_num_rows($query) == 1) // checks if a user name with that password exsists
            {
                    $row = mysql_fetch_assoc($query); // Put it to an associative array                    
                    return $row['user_id'];                      
            }
            else 
	   		{  
				return false;   
            }
   
    }

}


?>

login.php

<?php session_start();

include_once ('database.php'); // This is the location of your database class in your server
    $con= new database(); // create the database object
   
      if(isset($_POST['Submit'])){   // Check if the form is actually submitted
        if($_POST['username']!='' && $_POST['password']!='')
        {
            $output = $con->login($_POST['username'],$_POST['password']);
            if($output)
			{  //check the username & password
				
				$_SESSION['user_id'] = $output;  
                $_SESSION['logged_in'] = "ok";
				
				header("Location: menu.php");
				exit;					
            }
			else
			{
            	$error = 'Incorrect Login Details ...Try again later!<br>';   
            }
           
        }
        else
		{
            $error = 'Username Or Password Field is Empty..Please Check again!<br>';
        }
    }

?>

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Lakkam Trade Center</title>
<meta name="keywords" content="" />
<meta name="description" content="" />

</head>
<body>
<div id="Layer1"><img src="images/login.jpg" alt="" width="149" height="132" /></div>

<p>&nbsp;</p>
<div align="center" class="style1" id="Layer2">Administrator Login </div>
<div id="Layer3">
<form id="form1" name="form1" method="post" >
  <p>Username
    <input type="text" name="username" />
  </p>
  <p>&nbsp;</p>
  <p>Password
    &nbsp;<input type="password" name="password" />  
    </p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>
    <input type="submit" name="Submit" value="Login" />
	<input type="reset" name="Reset" value="Reset" />
	 <?php if(isset($error)){ echo "<span class=\"style6\">$error</span>";} //display errors?> 
  </p>
</div>
<div id="main">

<div id="header"></div>


</body>
</html>

Thanks for providing me the code..but still it is not working..And I cant figure it out whats wrong ...

The $con variable is only a local variable to your constructor method. When you reach the end of the method, your $con is no onger valid. It should be a class variable if you want to keep it around to use in your other methods.

Since you are trying to set this up as a class I would also use the $con variable in the mysql_query function (mysql_query($sql, $con)) just to avoid any confusion.

If u r still getting error, post ur error.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.