I am new at designing websites and I recently wanted to add login/registration forms to my website I have a database and have coded all of the forms but when I attempt to register I am unable to because my information is not added to the database. I have been working on this for a while any advice on how to better my forms and registration system would be more than helpful. Thanks in advance!
Here are my forms:
Registration:
<?php
session_start();
include "dbConfig.php";
if (isset($_GET["op"]) == "login") {
if (!$_POST["username"] || !$_POST["password"]) {
die("You need to provide a username and password.");
}
// Create query
$q = "SELECT * FROM `gd_database` "
."WHERE `username`='".$_POST["username"]."' "
."AND `password`=PASSWORD('".$_POST["password"]."') "
."LIMIT 1";
// Run query
$r = mysql_query($q);
if ( $obj = #mysql_fetch_object($r) ) {
// Login good, create session variables
$_SESSION["valid_id"] = $obj->id;
$_SESSION["valid_user"] = $_POST["username"];
$_SESSION["valid_time"] = time();
// Redirect to member page
Header("Location: members.php");
} else {
// Login not successful
die("Sorry, could not log you in. Wrong login information.");
}
} else {
echo "<form action=\"?op=login\" method=\"POST\">";
echo "Username: <input name=\"username\" size=\"15\">";
echo "Password: <input type=\"password\" name=\"password\" size=\"8\">";
echo "<input type=\"submit\" value=\"Login\">";
echo "</form>";
}
?>
Login:
<?php
session_start();
include "dbConfig.php";
if (isset($_GET["op"]) == "login") {
if (!$_POST["username"] || !$_POST["password"]) {
die("You need to provide a username and password.");
}
// Create query
$q = "SELECT * FROM `gd_database` "
."WHERE `username`='".$_POST["username"]."' "
."AND `password`=PASSWORD('".$_POST["password"]."') "
."LIMIT 1";
// Run query
$r = mysql_query($q);
if ( $obj = #mysql_fetch_object($r) ) {
// Login good, create session variables
$_SESSION["valid_id"] = $obj->id;
$_SESSION["valid_user"] = $_POST["username"];
$_SESSION["valid_time"] = time();
// Redirect to member page
Header("Location: members.php");
} else {
// Login not successful
die("Sorry, could not log you in. Wrong login information.");
}
}
else
{
echo "<form action=\"?op=login\" method=\"POST\">";
echo "Username: <input name=\"username\" size=\"15\">";
echo "Password: <input type=\"password\" name=\"password\" size=\"8\">";
echo "<input type=\"submit\" value=\"Login\">";
echo "</form>";
}
?>
Your login and registration scripts are the same code and they assume that you already have an account are trying to verify the credentials. You'll need to insert the data from the form into the database with an INSERT statement before anything else. Right now, you're just checking for accounts in an empty table.
Look up some tutorials for registering users. Tutsplus is nice.
here is a code for registration
register.php
<?php
include ("dbConfig.php");
if ( $_GET["op"] == "reg" )
{
$bInputFlag = false;
foreach ( $_POST as $field )
{
if ($field == "")
{
$bInputFlag = false;
}
else
{
$bInputFlag = true;
}
}
if ($bInputFlag == false)
{
die( "Problem with your registration info. "
."Please go back and try again.");
}
$q = "INSERT INTO `dbUsers` (`username`,`password`,`email`) "
."VALUES ('".$_POST["username"]."', "
."PASSWORD('".$_POST["password"]."'), "
."'".$_POST["email"]."')";
$r = mysql_query($q);
if ( !mysql_insert_id() )
{
die("Error: User not added to database.");
}
else
{
Header("Location: register.php?op=thanks");
}
}
elseif ( $_GET["op"] == "thanks" )
{
echo "<h2>Thankyou for registering!</h2>";
}
else
{
echo "<form action=\"?op=reg\" method=\"POST\">\n";
echo "Username: <input name=\"username\" MAXLENGTH=\"16\"><br />\n";
echo "Password: <input type=\"password\" name=\"password\" MAXLENGTH=\"16
\">\n";
echo "Email Address: <input name=\"email\" MAXLENGTH=\"25\"><br />\n";
echo "<input type=\"submit\">\n";
echo "</form>\n";
}
?>
inorder to add data into your database you need to use a query INSERT.hope this code would help you in solving your problem.
Related
I want to send a message from a user (user A) to another user (user B) which those users are connected each other in the database. To be more specific.
We keep the connection of the users in a table in the database which we called friends. In this table we have two columns, username and friend.
I have the code in order to send data between the users but it doesn't perform any checking in order to see if the user A who wants to send a message to the user B are connected to each other. If the users are connected I want to allow them to send the message and if they are not I want to echo a notification that they are not allowed to send a message because they are not connected.
I can understand that I want an if condition where I perform the check to see if the users are connected and have the appropriate code below and if it is not connected then output the notification described above.
How can I create this checking?
I am using php and mysql
HERE IS MY CODE...
<?php
include_once 'header.php';
if (!$loggedin) die();
if (isset($_GET['view'])) {
$view = sanitizeString($_GET['view']);
} else {
$view = $username;
}
if (isset($_POST['text'])){
$text = sanitizeString($_POST['text']);
if ($text != ""){
$pm = substr(sanitizeString($_POST['pm']),0,1);
$time = time();
queryMysql("INSERT INTO messages VALUES(NULL, '$username', '$view', '$pm', $time, '$text')");
}
}
if ($view != "") {
if ($view == $username) {
$name1 = $name2 = "Your";
} else {
$name1 = "<a href='members.php?view=$view'>$view</a>'s";
$name2 = "$view's";
}
echo "<div class='main'><h3>$name1 Messages</h3>";
showProfile($view);
echo <<<_END
<form method='post' action='messages.php?view=$view'>
Type here to leave a message:<br />
<textarea name='text' cols='40' rows='3'></textarea><br />
Public<input type='radio' name='pm' value='0' checked='checked' />
Private<input type='radio' name='pm' value='1' />
<input type='submit' value='Post Message' /></form><br />
_END;
if (isset($_GET['erase'])) {
$erase = sanitizeString($_GET['erase']);
queryMysql("DELETE FROM messages WHERE id=$erase AND recip='$username'");
}
$query = "SELECT * FROM messages WHERE recip='$view' ORDER BY time DESC";
$result = queryMysql($query);
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j) {
$row = mysql_fetch_row($result);
if ($row[3] == 0 || $row[1] == $username || $row[2] == $username) {
echo date('M jS \'y g:ia:', $row[4]);
echo " <a href='messages.php?view=$row[1]'>$row[1]</a> ";
if ($row[3] == 0) {
echo "wrote: "$row[5]" ";
} else {
echo "whispered: <span class='whisper'>" . ""$row[5]"</span> ";
}
if ($row[2] == $username) {
echo "[<a href='messages.php?view=$view" . "&erase=$row[0]'>erase</a>]";
}
echo "<br>";
}
}
}
if (!$num) {
echo "<br /><span class='info'>No messages yet</span><br /><br />";
}
echo "<br /><a class='button' href='messages.php?view=$view'>Refresh messages</a>";
?>
</div><br /></body></html>
The checking system for my question is the below and it works..
<?php
include_once 'header.php';
if (!$loggedin) die();
if (isset($_GET['view'])) $view = sanitizeString($_GET['view']);
else $view = $username;
$result1 = mysql_num_rows(queryMysql("SELECT username,friend FROM friends
WHERE username='$username' AND friend='$view'"));
$result2 = mysql_num_rows(queryMysql("SELECT username,friend FROM friends
WHERE username='$view' AND friend='$username'"));
if (($result1 + $result2) > 1)
{
//REST OF THE CODE
}
?>
what we are doing is that for the result1 we are checking if the logged in username($username) is connected with the viewed profile ($view) and for the result2 we are doing vice versal, to be more specific we are checking in the result2 that if the username of the viewed profile($view) is connected with the ($username) then in the if statement we check that if those two result has more than one row in the table then they are both connected.
PS: sorry for my bad english
Im new to PHP, login.php make you use your username instead of your email. How do you make it where I can have user's login just via email, an password instead of them using there username an password.
Login.php
<?php
session_start();
// Header file
require_once "views/template/header.php";
if ($_GET["op"] == "login")
{
if (!$_POST["username"] || !$_POST["password"])
{
die("You need to provide your e-mail and password.");
}
// Create query
$q = "SELECT * FROM `users` "
."WHERE `username`='".$_POST["username"]."' "
."AND `password`=PASSWORD('".$_POST["password"]."') "
."LIMIT 1";
// Run query
$r = mysql_query($q);
if ( $obj = #mysql_fetch_object($r) )
{
// Login good, create session variables
$_SESSION["valid_id"] = $obj->id;
$_SESSION["valid_user"] = $_POST["username"];
$_SESSION["valid_time"] = time();
// Redirect to member page
Header("Location: members.php");
}
else
{
// Login not successful
die("Sorry, could not log you in. Wrong login information.");
}
}
else
{
//If all went right the Web form appears and users can log in
echo "<form action=\"?op=login\" method=\"POST\">";
echo "Username: <input name=\"username\" size=\"15\"><br />";
echo "Password: <input type=\"password\" name=\"password\" size=\"8\"><br />";
echo "<input type=\"submit\" value=\"Login\">";
echo "</form>";
echo "Don't have account <a href='register.php'>create account now!</a>";
}
require_once "views/template/footer.php";
?>
Register.php
<?php
// dbConfig.php is a file that contains your
// database connection information. This
// tutorial assumes a connection is made from
// this existing file.
require_once "views/template/header.php";
//Input vaildation and the dbase code
if ( $_GET["op"] == "reg" )
{
$bInputFlag = false;
foreach ( $_POST as $field )
{
if ($field == "")
{
$bInputFlag = false;
}
else
{
$bInputFlag = true;
}
}
// If we had problems with the input, exit with error
if ($bInputFlag == false)
{
die( "Problem with your registration info. "
."Please go back and try again.");
}
$profile=$_POST['profilename'];
$password=$_POST['password'];
$email=$_POST['email'];
$fname=$_POST['firstname'];
$lname=$_POST['lastname'];
// Fields are clear, add user to database
// Setup query
$q = "INSERT INTO users (`profilename`,`password`,`email`,`firstname`,`lastname`)
VALUES ('$profile','$password','$email','$fname','$lname')";
// Run query
$r = mysql_query($q);
// Make sure query inserted user successfully
if ( !mysql_insert_id() )
{
die("Error: User not added to database.");
}
else
{
// Redirect to thank you page.
Header("Location: register.php?op=thanks");
}
} // end if
//The thank you page
elseif ( $_GET["op"] == "thanks" )
{
echo "<h2>Thanks for registering!</h2>";
}
//The web form for input ability
else
{
echo "<form action=\"?op=reg\" method=\"POST\">\n";
echo "Profile Name: <input name=\"profilename\" MAXLENGTH=\"16\"><br />\n";
echo "Password: <input type=\"password\" name=\"password\" MAXLENGTH=\"16\"><br />\n";
echo "Email Address: <input name=\"email\" MAXLENGTH=\"25\"><br />\n";
echo "First Name: <input name=\"firstname\" MAXLENGTH=\"25\"><br />\n";
echo "Last Name: <input name=\"lastname\" MAXLENGTH=\"25\"><br />\n";
echo "<input value='Submit' type=\"submit\">\n";
echo "</form>\n";
}
// EOF
require_once "views/template/footer.php";
?>
Just look for the email instead of the username:
// Create query
$q = "SELECT * FROM `users` "
."WHERE `email`='".$_POST["username"]."' "
."AND `password`=PASSWORD('".$_POST["password"]."') "
."LIMIT 1";
And change your form label:
echo "Email: <input name=\"username\" size=\"15\"><br />";
That's the quickest fix. Obviously to be more thorough you'll want to replace all instances of "Username" or $_POST['username'] in your login script with email, and you should stop using the mysql_* library since it's deprecated and soon to be removed.
i create php files that check user login in. If the user and password is correct, user can visit the catalog page. However there are some problems with the session. After reopening browser it still display the hidden data. I know the session will be closed when i close the browser but this case seems weird. This is the login form:
<html>
<body>
<?php
$LabelLogin=array("login"=>"login",
"password"=>"password",
);
echo "<h1> Login and Register Page </h1>";
echo "<form action='CheckLoginDetail.php' method=POST>";
foreach($LabelLogin as $keys =>$values)
{
if($keys=='password')
{
echo "$values <input type='password' name='$keys' /><br/>";
}
else
{
echo "$values <input type='text' name='$keys' /><br/>";
}
}
echo "<input type='submit' value='submit' />";
echo "<br/>click <a href='register.php'>here<a/> to register if you don't have an accout <br/>";
echo "</form>";
?>
</body>
2nd CheckLoginDetail.php
<?php
session_start();
include("connect.inc");
$connect=mysqli_connect($host,$username,$password,$dbname) or die ("can't connect to server");
$labels=array("login"=>"login",
"password"=>"password");
foreach($_POST as $keys =>$values)
{
if(empty($values))
{
$empty_values[]=$keys;
}
elseif(!preg_match("/^[A-Za-z0-9_]+$/",$values))
{
$invalid_values[]=$keys;
}
else
{
$data[$keys]=$values;
}
}
if(#sizeof($empty_values)>0 or #sizeof($invalid_values)>0)
{
if(#sizeof($empty_values)>0)
{
echo "login name or password or both can not be empty !";
}
if(#sizeof($invalid_values)>0)
{
echo "values contain invalid characters";
}
include("FrontPage.php");
exit();
}
else
{
foreach($data as $keys =>$values)
{
$clean_data[$keys]=mysqli_real_escape_string($connect,strip_tags(trim($values)));
}
$query="SELECT LoginName and Password FROM yugimemberinfo WHERE LoginName='";
foreach($clean_data as $keys =>$values)
{
if($keys=="login")
{
$query.="$values'";
}
if($keys=="password")
{
$values=md5($values);
$query.=" AND Password='$values'";
}
}
$result=mysqli_query($connect,$query) or die("can't execute query ".mysqli_error($connect));
if(mysqli_num_rows($result)==0)
{
echo "login fail";
include("FrontPage.php");
exit();
}
else
{
$_SESSION['access']="yes";
echo "login succesfully !<br/>";
echo "Here are two options for you :<br/>";
echo "<ul>
<li><a href='ShowCatalog.php'>Go to Card Catalog</a></li>
<li><a href='search_form.php'>Searching for your cards</a></li>
</ul>";
$query_insert="INSERT INTO yugimember (LoginName,LoginTime) VALUES(";
foreach($clean_data as $keys =>$values)
{
//echo "$keys =>$values<br/>";
if($keys=="login")
{
$query_insert.="'$values',";
}
}
//insert login name and time to yugimember
$query_insert.="'".date("Y-m-d H:i:s")."')";
$result=mysqli_query($connect,$query_insert) or die ("can't execute query line 62");
}
}
?>
if users login successfully, they can lick to the link that take them to another site called "ShowCatalog.php"
<?php
session_start();
include("connect.inc");
$connect=mysqli_connect($host,$username,$password,$dbname) or die ("can't connect to server");
if(#$_SESSION['access'] != 'yes')
{
include("FrontPage.php");
exit();
}
$query="SELECT * FROM dragon ";
$result=mysqli_query($connect,$query) or die("can't execute query");
echo "<hr/>";
while($row=mysqli_fetch_assoc($result))
{
extract($row);
echo $type."<br/>";
echo $CardName."<br/>";
echo $atk." \ ".$def."<br/>";
echo $Description;
echo "<br/>".$picture."<br/>";
echo "<br/>";
echo "<a href='../dragon/{$picture}'><img src='../dragon/{$picture}' height='300' width='300'></a>";
echo "<hr/>";
}
?>
I make the ShowCatalog.php only display data for user logining in. However when i login in and close the browser then reopen it the ShowCatalog.php the data is stilled appear.
Not sure but when you do this :
if(#$_SESSION['access'] != 'yes')
If the session does not exist (because you closed your browser), maybe it will bypass this condition.
Try :
if (!isset($_SESSION['access']) | $_SESSION['access'] != 'yes')
I am trying to check the login, then trying to echo basic user info. Thanks in advance for everyones help. Any suggestions on why I'm unable to echo row data based on a specific logged in user?
<?php
<?php
session_start();
// dBase file
include "config.php";
ini_set('display_errors', 1);
if (isset($_GET["op"] ) && $_GET["op"] == "login")
{
if (!$_GET["username"] || !$_GET["password"])
{
die("You need to provide a username and password.");
}
// Create query
$q = "SELECT * FROM `users` "
."WHERE `username`='".$_GET["username"]."' "
."AND `password`=PASSWORD('".$_GET["password"]."') "
."LIMIT 1";
// Run query
$r = mysql_query($q);
$row = mysql_assoc_array($r);
$count = mysql_num_rows($r);
if ($obj = mysql_fetch_object($r) && $count == 1)
{
// Login good, create session variables
$_SESSION["id"] = $row['id'] = $obj->id;
$_SESSION["user"] = $row['username'] = $obj->username;
$_SESSION["time"] = time();
// Redirect to member page
Header("Location: welcome.php");
}
else
{
// Login not successful
die("Sorry, could not log you in. Wrong login information.");
header("Location: login2.php");
}
}
{
//If all went right the Web form appears and users can log in
echo "<form action=\"?op=login\" method=\"GET\">";
echo "Username: <input name=\"username\" name=\"username\" size=\"32\"><br />";
echo "Password: <input type=\"password\" name=\"password\" size=\"32\"><br />";
echo "<input type=\"submit\" value=\"Login\">";
echo "</form>";
}
?>
You're using mysql_fetch_object so you need to do:
$_SESSION["user"] = $obj->username;
Rather than:
$_SESSION["user"] = $row['username'];
login.php
// Create query
$q = "SELECT * FROM `dbUsers` "
."WHERE `username`='".$_POST["username"]."' "
."AND `password`=PASSWORD('".$_POST["password"]."') "
."LIMIT 1";
// Run query
$r = mysql_query($q);
if ( $obj = #mysql_fetch_object($r) )
{
// Login good, create session variables
$_SESSION["valid_id"] = $obj->id;
$_SESSION["valid_user"] = $_POST["username"];
$_SESSION["valid_time"] = time();
// Redirect to member page
Header("Location: members.php");
}
else
{
// Login not successful
die("Sorry, could not log you in. Wrong login information.");
}
}
else
{
//If all went right the Web form appears and users can log in
echo "<form action=\"?op=login\" method=\"POST\">";
echo "Username: <input name=\"username\" size=\"15\"><br />";
echo "Password: <input type=\"password\" name=\"password\" size=\"8\"><br />";
echo "<input type=\"submit\" value=\"Login\">";
echo "</form>";
}
?>
unable to login with the above code.
error at if ( $obj = #mysql_fetch_object($r) )
error message for the code above:Possible accidental assignment, assignments in conditions should be avoided
that last else is badly nested with the if/else. There are two else's and only 1 if.