Hi,
With resources on the internet I have created two versions of a login page :- one with mysql_fetch_object and the other without it. I would like to understand which approach is a better and why.
Following is the code with mysql_fetch_object :-
<?php
session_start();
include "dbconnect.php";
if(isset($_GET["op"]) == "login")
{
if(!$_POST["username"] || !$_POST["password"])
{
die("You need to provide a username and password.");
}
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
$q = "SELECT * FROM users WHERE username = '$username' AND password = '$password'");
$r = mysql_query($q);
if ( $obj = @mysql_fetch_object($r) )
{
// Login good, create session variables
$_SESSION["valid_localid"] = $obj->id;
$_SESSION["valid_localuser"] = $_POST["username"];
$_SESSION["valid_localtime"] = time();
// Redirect to member page
Header("Location: homepage.php");
}
else
{
die("Sorry, could not log you in. Wrong login information.");
}
}
else
{
?>
<html>
<head>
<title>PHP Session</title>
</head>
<body>
<h3>Login Form</h3>
<form action="?op=login" method="POST">
<label>Username</label>
<input type="text" name="username">
<br>
<label>Password</label>
<input type="password" name="password">
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
<?php
}
?>
Following is the code without mysql_fetch_object :-
<?php
session_start();
include "dbconnect.php";
if(isset($_GET["op"]) == "login")
{
if(!$_POST["username"] || !$_POST["password"])
{
die("You need to provide a username and password.");
}
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
$q = mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'");
$r = mysql_fetch_array($q);
$num_results = mysql_num_rows($q);
if($num_results > 0)
{
$_SESSION["valid_user"] = $_POST["username"];
$_SESSION["timeout"] = time();
Header("Location: aboutuser.php");
}
else
{
die("Sorry, could not log you in. Wrong login information.");
}
}
else
{
?>
<html>
<head>
<title>PHP Session</title>
</head>
<body>
<h3>Login Form</h3>
<form action="?op=login" method="POST">
<label>Username</label>
<input type="text" name="username">
<br>
<label>Password</label>
<input type="password" name="password">
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
<?php
}
?>
Please help me find which is a better approach and why. Since this code is from someone else, I was unable to understand how form action is working here. Please help me in understanding (action="?op=login") part.
Thanks