Why won't my SELECT * FROM work? - php

Here is the code for my entire index page, which includes a register and a login. For some reason, the register part works fine, and it is inserting correctly. Yet, the login part is not working, as whenever I call the $queryrun(mysql_query($query)) on the SELECT * FROM, it does not work.
<?php
require('includes/dbconnect.php');
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$password = md5($password);
$logemail = $_POST['logemail'];
$logpassword = $_POST['logpassword'];
$logpassword = md5($logpassword);
// Register Script
if (isset($firstname) && !empty($firstname) && !empty($lastname) && !empty($email) && !empty($password)) {
$query = "INSERT INTO users VALUES('', '$firstname', '$lastname', '$email', '', 'm', '9', '$password', 'bio'";
$queryrun = mysql_query($query);
} else {
echo 'Please fill out all of the form fields';
}
// Login Script
if (!empty($logemail) && !empty($logpassword)){
$query = "SELECT * FROM users WHERE email = '$email' AND password = '$password'";
$queryrun = mysql_query($query);
while ($row = mysql_fetch_assoc($queryrun)) {
$logemail = $row['logemail'];
}
echo $logemail;
$numrows = mysql_num_rows($query);
if ($numrows > 0){
echo 'User exists';
} else {
echo 'User does not exist';
}
} else {
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form action="index.php" method="POST">
Firstname: <input type="text" name="firstname" /><br />
Lastname: <input type="text" name="lastname" /><Br />
Email: <input type="text" name="email" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" value="Submit" />
</form>
<br /><hr />
<br />
Login:<br />
<form action="index.php" method="POST">
Email:<input type="text" name="logemail" /><br />
Password: <input type="password" name="logpassword" /><br />
<input type="submit" value="Log in" /><br />
</form>
</body>
</html>
The connection to the database is fine because the register part code works, it's just the login code is returning nothing and saying that the user does note exist, when the user actually does exist

Your form field is $logemail while your mysql statement uses $email.
To get this working looks like you want:
$query = "SELECT * FROM users WHERE email = '$logemail' AND password = '$logpassword'";
But as John Conde mentions there are significant security issues.

What version of PHP are you using? This extension is deprecated as of PHP 5.5.0, you really should be using mysqli or PDO.
also
if (!empty($logemail) && !empty($logpassword)){
$query = "SELECT * FROM users WHERE email = '$email' AND password = '$password'";
you are checking for $logemail and $logpassword but putting $email and $password in the query string... also use {} in your strings for php variables. it helps keep string concatenation from getting confusing and you can use associated arrays in the string
echo "This is my string and this is the number {$number}. this is the value in my array: {$arrayvar["something"]}.";

Related

Why does my Register form still not input data into my MySQL tables

I'm trying to link a register page with my login page to allow new users to register an account to use on my application. I've linked the form up to my tbl_Users table on MySQL in which holds all the information that the users would input into this form. I've properly set everything up using queries and such and the form displays properly at the very least. However when I click submit, the page just refreshed with the fields now empty again and no new data within my table on the database. Where am I going wrong? (Extra-note: I'm still in the process of coding in the safety code to prevent sql-injections)
ConnectorCode.php
<?php
$conn = mysqli_connect("localhost", "b4014107", "Win1", "b4014107_db2") or die (mysqli_connect_error());
?>
Register.php
<?
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
include('ConnectorCode.php');
if(isset($_POST['submit'])) {
$FName = $_POST['First_Name'];
$LName = $_POST['Last_Name'];
$Email = $_POST['Email'];
$UName = $_POST['User_Name'];
$Password = $_POST['Password'];
$FName = mysqli_real_escape_string($conn, $FName);
$LName = mysqli_real_escape_string($conn, $LName);
$Email = mysqli_real_escape_string($conn, $Email);
$UName = mysqli_real_escape_string($conn, $UName);
$Password = mysqli_real_escape_string($conn, $Password);
$sql = "SELECT Email FROM tbl_Users WHERE Email='$Email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
echo "Sorry, the email you are trying to enter already exists";
}
else
{
$query = mysqli_query($conn, "INSERT INTO tbl_Users(First_Name, Last_Name, Email, User_Name, Password) VALUES ('$FName', '$LName', '$Email', '$UName', '$Password')");
if($query)
{
echo "Thank you for registering";
}
header('Location: Index.php');
}
}
?>
<!DOCTYPE HTML>
<head>
<title>Register</title>
</head>
<body>
<h1> Register Page </h1>
<p> Please fill in the form to register <p>
<form method="post" action="">
<fieldset>
First Name: <br />
<input name="First_Name" type="text" class="input" size="25" required /> <br /> <br />
Last Name: <br />
<input name="Last_Name" type="text" class="input" size="25" required /> <br /> <br />
Email: <br />
<input name="Email" type="email" class="input" size="25" required /> <br /> <br />
Username: <br />
<input name="User_Name" type="text" class="input" size"25" required /> <br /> <br />
Password: <br />
<input name="Password" type="password" class="input" size="25" required /> <br /> <br/>
<input type="submit" name="submit" value="Register!" />
</fieldset>
</form>
</body>
</html>
You do not meet the condition isset($_POST['VALUES']) because you don't have field with name="VALUES".
Change
if(isset($_POST['VALUES'])) {
to
if(isset($_POST['submit'])) {
You had a lot missing...
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
require_once 'ConnectorCode.php';
if(isset($_POST['submit']))
{
$FName = mysqli_real_escape_string($conn, $_POST['First_Name']);
$LName = mysqli_real_escape_string($conn, $_POST['Last_Name']);
$Email = mysqli_real_escape_string($conn, $_POST['Email']);
$UName = mysqli_real_escape_string($conn, $_POST['User_Name']);
$Password = mysqli_real_escape_string($conn, $_POST['Password']); // why did you need to repeat this all twice?
$sql = "SELECT * FROM tbl_Users WHERE Email='$Email'"; // ? didn't understand why you was asking for the Email using the Email...
$result = $conn->query($sql);
if(count($result) == 0)
{
$insert_sql = "INSERT INTO tbl_Users (First_Name,Last_Name,Email,User_Name,Password) VALUES ('$FName','$LName','$Email','$UName','$Password')";
if($conn->query($insert_sql)) // You forgot to query this
{
echo "Thank you for registering";
header('Location: index.php'); // lowercase i
exit; // you forgot this
}
}
else
{
echo "Sorry, that email already exists!";
}
$conn->close(); // you forgot this
}
?>
Hope this helps...

Check if username is being used

I'm wondering if and how I could check if a username is being used.
I heard you can do this with jQuery but i just want something simple since I'm a beginner.
I have tried it but i can't seam to get it right. I just have it connected to a mysql database but since when a username with the same password as another account tries to logon, theres an issue, so i need this to stop people adding multiple usernames.
Here is my simple code for the registration form and the php
<form action="" method="POST">
<p><label>name : </label>
<input id="password" type="text" name="name" placeholder="name" /></p>
<p><label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" /></p>
<p><label>E-Mail : </label>
<input id="password" type="email" name="email"/></p>
<p><label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" /></p>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" name="submit" value="Register" />
</form>
</div>
<?php
require('connect.php');
// If the values are posted, insert them into the database.
if (isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$query = "INSERT INTO `user` (username, password, email, name) VALUES ('$username', '$password', '$email', '$name')";
$result = mysql_query($query);
if($result){
}
}
?>
For starters you don't want to just rely on something like unique field for doing this, of course you will want to add that attribute to your username column within your database but above that you want to have some sort of frontal protection above it and not rely on your database throwing an error upon INSERT INTO, you're also going to want to be using mysqli for all of this and not the old version, mysql. It's vulnerable to exploitation and no longer in common practice, here's what each of your files should look like:
connect.php
<?php
$conn = mysqli_connect("localhost","username","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
register.php
<form action="insertuser.php" method="POST">
Username:
<input type="text" name="username" placeholder="Username" />
<br />
Password:
<input type="password" name="password" placeholder="Password" />
<br />
Name:
<input type="text" name="name" placeholder="Name" />
<br />
Email address:
<input type="text" name="email" placeholder="Email address" />
<br /><br />
<input type="submit" value="Register" />
</form>
<?php
// If there's an error
if (isset($_GET['error'])) {
$error = $_GET['error'];
if ($error == "usernametaken") {
echo "<h4>That username is taken!</h4>";
} elseif ($error == "inserterror") {
echo "<h4>Some kind of error occured with the insert!</h4>";
} else {
echo "<h4>An error occured!</h4>";
}
echo "<br />";
}
?>
Already have an account? Login here
insertuser.php
<?php
// Stop header errors
ob_start();
// Check if form has been posted
if (isset($_POST['username'])){
// Requre database connection file
require('connect.php');
// Clean the variables preventing SQL Injection attack
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$name = mysqli_real_escape_string($conn, $_POST['name']);
// Check if the username exists
// Construct SELECT query to do this
$sql = "SELECT id FROM user WHERE username = '".$username."';";
$result = mysqli_query($conn, $sql);
$rowsreturned = mysqli_num_rows($result);
// If the username already exists
if ($rowsreturned != 0) {
echo "Username exists, redirecting to register.php with an error GET variable!";
// Redirect user
header('Location: register.php?error=usernametaken');
} else {
// Construct the INSERT INTO query
$sql = "INSERT INTO user (username, password, email, name) VALUES ('".$username."', '".$password."', '".$email."', '".$username."');";
$result = mysqli_query($conn, $sql);
if($result){
// User was inserted
echo "User inserted!";
/* DO WHATEVER YOU WANT TO DO HERE */
} else {
// There was an error inserting
echo "Error inserting, redirecting to register.php with an error GET variable!";
// Redirect user
header('Location: register.php?error=inserterror');
}
}
}
?>
Good luck with whatever you're working on and I hope this helps!
James
if (isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$query = "select username from user where username = '$username'";
$res = mysql_query($query);
$rows = mysqli_num_rows($res);
if ($rows > 0) {
print 'Username already exists...';
} else {
$query = "INSERT INTO `user` (username, password, email, name) VALUES ('$username', '$password', '$email', '$name')";
$result = mysql_query($query);
if($result){
}
}
}
Here is another example :) , succes.
<?php
//Set empty variables.
$usernameError = $emailError = $passwordError = $nameError = $okmsg = "";
$username = $password = $email = $name = "";
if (isset($_POST['submit'])) {
//Check if empty labels form
if (empty($_POST['name'])) {
$userError = "The 'name' is required.";
echo '<script>window.location="#registrer"</script>';
} else { $name = $_POST['name']; }
if (empty($_POST['email'])) {
$emailError = "El 'Email' es requerido.";
echo '<script>window.location="#registrer"</script>';
} else {
$email = $_POST['email'];
//Check only contain letters and whitespace.
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailError = "El 'Email' is not valid. ";
echo '<script>window.location="#registrer"</script>';
}
}
if (empty($_POST['password'])) {
$passwordError = "The 'password' is requiered.";
echo '<script>window.location="#registrer"</script>';
} else {
$password = $_POST['password'];
}
}
//Check if correctly filled
if ($name && $username && $email && $password) {
require('connect.php');
//Query SQL
$sql = "SELECT * FROM user WHERE username='$username'"; //String SQL
$query = mysqli_query($ConDB, $sql);//Query
//Securite
$username = mysqli_real_escape_string($ConDB, $username);
$password = mysqli_real_escape_string($ConDB, $username);
$passw = sha1($password);//For securite.
$name = mysqli_real_escape_string($ConDB, $username);
$email = mysqli_real_escape_string($ConDB, $username);
if ($existe = mysqli_fetch_object($query)) {
$usernameError = "The 'Username' is already exists.";
echo '<script>window.location="#registrer"</script>';
} else {
$sql = "INSERT INTO user (username, password, email, name) VALUES ('$username', '$passw', '$email', '$name')";
mysqli_query($ConDB, $sql);
$okmsg = "Register with succes.";
mysqli_close($ConDB);//Close conexion.
echo '<script>window.location="#registrer"</script>';
}
}
?>
<a name="registrer"></a>
<form action="" method="POST">
<p><label>name : </label>
<input id="password" type="text" name="name" placeholder="name" /></p>
<?php echo $nameError; ?>
<p><label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" /></p>
<?php echo $usernameError; ?>
<p><label>E-Mail : </label>
<input id="password" type="email" name="email"/></p>
<?php echo $emailError; ?>
<p><label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" /></p>
<?php echo $passwordError; ?>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" name="submit" value="Register" />
<?php echo $okmsg; ?>
</form>
--
-- DATA BASE: `user`
--
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
CREATE TABLE user (
id int(11) unsigned not null auto_increment primary key,
name varchar(50) not null,
email varchar(80) not null unique,
username varchar(30) not null unique,
password varchar(40) not null
)engine=InnoDB default charset=utf8 collate=utf8_general_ci;
You can try use jQuery AJAX for what you want.
First, add this to your registration.php file
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// when user submit the form
$('form').on('submit', function(event){
$.ajax({
url: "check_username.php",
type: "POST",
dataType: "JSON",
data: {
username: $("#username").val() // get the value from username textbox
},
success: function(data){
if(data.status == "exists"){
alert('Username already existed');
}
else{
$('form').submit();
}
},
});
event.preventDefault();
});
</script>
So now your registration.php file will look like this
registration.php
<form action="" method="POST">
<p>
<label>name : </label>
<input id="password" type="text" name="name" placeholder="name" />
</p>
<p>
<label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" />
</p>
<p>
<label>E-Mail : </label>
<input id="password" type="email" name="email"/>
</p>
<p>
<label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" />
</p>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" name="submit" value="Register" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// when user typing in 'username' textbox
$('form').on('submit', function(event){
$.ajax({
url: "check_username.php",
type: "POST",
dataType: "JSON",
data: {
username: $("#username").val() // get the value from username textbox
},
success: function(data){
if(data.status == "exists"){
alert('Username already existed');
}
else{
$('form').submit();
}
},
});
event.preventDefault();
});
</script>
Then create php file named check_username.php to check the username submitted by user if it is already existed in database or still available.
check_username.php
<?php
// Check if 'username' textbox is not empty
if(!empty($_POST['username'])){
$username = trim(mysqli_real_escape_string($_POST['username']));
// Check the database if the username exists
$query = "SELECT username FROM `user` WHERE username = '".$username."'";
$result = mysqli_query($query);
if(mysqli_num_rows($result) > 0){
// if username already exist
// insert into array, to be sent to registration.php later
$response['status'] = 'exists';
}
else{
// if username available
$response['status'] = 'available';
}
}
header('Content-type: application/json');
echo json_encode($response);
exit;
?>
Here is how it works:
1. When user click the register button, jQuery will call check_username.php.
2. Now in check_username.php it will check the database if the username submitted already exists or still available.
3. Whatever the result either exists or available, check_username.php will send the result back to registration.php as string contains 'exists' or 'available'.
4. registration.php now get the result and will check the result sent by check_username.php if it contain 'exists' or 'available'. If the string is 'exists' then alert will be triggered. If the string is 'available', the form will be submitted.

Why won't my log in page receive any information?

I made a login page for my website. The connection to the database is fine, and I am typing in to the login form the correct values that are in the database. I have a md5 on the password in both the database and the code. Yet, when I check to see if any rows come back, there are none. I would just like another set of eyes to look over what is probably a stupid mistake.
<?php
$email = $_POST['email'];
$password = $_POST['password'];
$password = md5($password);
$query = "SELECT * FROM users WHERE password = '$password' AND email='$email' AND activated='1'";
$queryrun = mysql_query($query);
while($row = mysql_fetch_assoc($queryrun)) {
$fname = $row['firstname'];
echo $fname;
}
$logincheck = mysql_num_rows($queryrun);
if ($logincheck > 0) {
echo 'good, you are in our database';
} else {
echo 'sorry, you are not in our database';
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
Login <br />
<form action="login.php" method="POST">
Email: <input type="text" name="email" />
Password: <input type="password" name="password" />
<input type="submit" value="Log in" />
</form>
</body>
</html>

how to allow users logged in to UPDATE / EDIT their profile settings/information

Question at hand:
How do I create the php code to let users who are logged into my site edit/update their profile settings/information?
I have 1 part working correctly for users to change their password, however, have no idea where to start when it comes to allowing users who are logged in to edit/update their other settings such as:
(1) nickname,
(2) country,
(3) date of birth,
(4) gender,
(5) motto and
(6) bio
I'll provide the php and html code below that I have that is working for changing password, but I know that I need more to let users change/edit/update their other information. I tried using what is below as a reference to create the php code for the other information, but it didn't work so I have no idea where to even begin! Any help will be much appreciated...
PHP reference code:
if($_POST['submit']=='Change')
{
$err = array();
if(!$_POST['password1'] || !$_POST['passwordnew1'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['password1'] = mysql_real_escape_string($_POST['password1']);
$_POST['passwordnew1'] = mysql_real_escape_string($_POST['passwordnew1']);
$row = mysql_fetch_assoc(mysql_query("SELECT id,username FROM members WHERE username='{$_SESSION['username']}' AND pass='".md5($_POST['password1'])."'"));
if($row['username'])
{
$querynewpass = "UPDATE members SET pass='".md5($_POST['passwordnew1'])."' WHERE username='{$_SESSION['username']}'";
$result = mysql_query($querynewpass) or die(mysql_error());
$_SESSION['msg']['passwordchange-success']='* You have successfully changed your password!';
}
else $err[]='Wrong password to start with!';
}
if($err)
$_SESSION['msg']['passwordchange-err'] = implode('<br />',$err);
header("Location: members.php?id=" . $_SESSION['username']);
exit;
}
HTML reference code:
<form action="" method="post">
<label class="grey" for="password1">Current Password:</label>
<input class="field" type="password" name="password1" id="password1" value="" size="23" />
<label class="grey" for="password">New Password:</label>
<input class="field" type="password" name="passwordnew1" id="passwordnew1" size="23" />
<input type="submit" name="submit" value="Change" class="bt_register" style="margin-left: 382px;" />
<div class="clear"></div>
<?php
if($_SESSION['msg']['passwordchange-err'])
{
echo '<div class="err">'.$_SESSION['msg']['passwordchange-err'].'</div>';
unset($_SESSION['msg']['passwordchange-err']);
}
if($_SESSION['msg']['passwordchange-success'])
{
echo '<div class="success">'.$_SESSION['msg']['passwordchange-success'].'</div>';
unset($_SESSION['msg']['passwordchange-success']);
}
?>
</form>
So how would I create the php code to make this work for users to be able to edit/update their own profile settings/information from the numeric list I provided above (1-6)?
And I know using mysqli/pdo is a better alternative to use, but I unfortunately need to use the old deprecated mysql_* stuff for this project at this time...
If you need more info, let me know ;)
EDIT:
Additional Question,
I'd assume too that I'd need to create variables for each column too such as:
$nickname = $_POST['nickname'];
$country = $_POST['country'];
etc...or is that not correct?
RE-EDIT:
Would something like this be applicable?
$id = $_SESSION['id'];
if ($_POST['country']) {
$country = $_POST['country'];
$nickname = $_POST['nickname'];
$DOB = $_POST['DOB'];
$gender = $_POST['gender'];
$motto = $_POST['motto'];
$bio = $_POST['bio'];
$sql = mysql_query("UPDATE members SET country='$country', nickname='$nickname', DOB='$DOB', gender='$gender', motto='$motto', bio='$bio' WHERE id='$id'");
exit;
}
$sql = mysql_query("SELECT * FROM members WHERE id='$id' LIMIT 1");
while($row = mysql_fetch_array($sql)){
$country = $row["country"];
$nickname = $row["nickname"];
$DOB = $row["DOB"];
$gender = $row["gender"];
$motto = $row["motto"];
$bio = $row["bio"];
}
Or am I way off base?
short version ;)
HTML file:
<form action="./change.php" method="post">
Nickname: <input type="text" name="nickname"><br />
Country: <input type="text" name="country"><br />
Date of birth: <input type="text" name="date_of_birth"><br />
Gender: <input type="text" name="gender"><br />
Motto: <input type="text" name="motto"><br />
Bio: <input type="text" name="bio"><br />
<input type="submit" value="Submit">
</form>
change.php:
<?php
function filter($date)
{
return trim(htmlspecialchars($date));
}
$nickname = filter($_POST['nickname'])
$country = filter($_POST['country'])
$date_of_birth = filter($_POST['date_of_birth'])
$gender = filter($_POST['gender'])
$motto = filter($_POST['motto'])
$bio = filter($_POST['bio'])
if (isUserLogIn)
{
//SQL update query
}
?>

Simple PHP + MySQL Form Not Working

Alright, so recently I watched a tutorial and coded along with it in Notepad++. I am attempting a simple MYSQL login/register form, but when I login- it gives me the "Wrong U/P" error echo I wrote. It saves everything in the database as the md5 and stuff. Here is my codes.
register.php
<?php
require('config.php');
if(isset($_POST['submit'])){
//Preform the verification of the nation
$email1 = $_POST['email1'];
$email2 = $_POST['email2'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
if($email1 == $email2) {
if($pass1 == $pass2) {
//All good. Carry on.
$name = mysql_escape_string($_POST['name']);
$lname = mysql_escape_string($_POST['lname']);
$uname = mysql_escape_string($_POST['uname']);
$email1 = mysql_escape_string($_POST['email1']);
$email2 = mysql_escape_string($_POST['email2']);
$pass1 = mysql_escape_string($_POST['pass1']);
$pass2 = mysql_escape_string($_POST['pass2']);
$pass1 = md5($pass1);
$sql = mysql_query("SELECT * FROM `users` WHERE `uname` = '$uname'");
if(mysql_num_rows($sql) > 0) {
echo "Sorry, that user already exists!";
exit();
}
mysql_query("INSERT INTO `users` (`id`, `name`, `lname`, `uname`, `email`, `pass`) VALUES (NULL, '$name', '$lname', '$uname', '$email1', '$pass1')");
}else{
echo "Sorry, your passwords do not match<br><br>";
exit();
}
}else{
echo "Sorry, your emails do not match.<br><br>";
}
}else{
$form = <<<EOT
<form action="register.php" method="POST">
First Name: <input type="text" name="name" /><br />
Last Name: <input type="text" name="lname" /><br />
Username: <input type="text" name="uname" /><br />
Email: <input type="text" name="email1" /><br />
Confirm Email: <input type="text" name="email2" /><br />
Password: <input type="password" name="pass1" /><br />
Confirm Password: <input type="password" name="pass2" /><br />
<input type="submit" value="Register" name="submit" />
</form>
EOT;
echo $form;
}
?>
login.php
<?php
require('config.php');
if(isset($_POST['submit'])){
$uname = mysql_real_escape_string($_POST['uname']);
$pass = mysql_real_escape_string($_POST['pass']);
$pass = md5($pass);
$sql = mysql_query("SELECET * FROM `users` where `uname` = '$uname' and `pass` = '$pass'");
if(mysql_num_rows($sql) > 0){
echo "You are now logged in.";
exit();
}else{
echo "Wrong U/P combination";
}
}else{
$form = <<<EOT
<form action="login.php" method="POST">
Username: <input tye="text" name="uname" /><br>
Password: <input type="password" name="pass" /><br>
<input type="submit" name="submit" value="Login" />
</form>
EOT;
echo "$form";
}
?>
and config.php
<?php
mysql_connect("localhost", "X", "X");
mysql_select_db("X");
?>
The config.php code is correct, but I am not giving away X.
As you can see, this code echos out an error for login.php if it's incorrect. It gives me that error even if it is correct. I used MD5 hash passes, so please help!
Firstly, you're using the ` tag in there - this should be ' .
You need to either interpolate or concatenate your variables; i.e; instead of
mysql_query("INSERT INTO `users` (`id`, `name`, `lname`, `uname`, `email`, `pass`) VALUES (NULL, '$name', '$lname', '$uname', '$email1', '$pass1')");
use;
mysql_query("INSERT INTO 'users' ('id', 'name', 'lname', 'uname', 'email', 'pass') VALUES (NULL, '{$name}', '{$lname}', '{$uname}', '{$email1}', '{$pass1}')");
Anyway, aside from some good practice, have a look at this line;
$sql = mysql_query("SELECET * FROM `users` where `uname` = '$uname' and `pass` = '$pass'");
Just a small typo ruining everything for you. Change SELECET to SELECT , and you should be good to go.
Best of luck!
Eoghan
you don't need the following lines:
$email2 = mysql_escape_string($_POST['email2']);
and
`$pass2 = mysql_escape_string($_POST['pass2']);`
2. run SELECET * FROM users in order to see that the user/pwd really made it to the DB
3. add echo "$uname $pass <br>"; to the login form to make sure that it passed correctly
The other two answers are correct, but you have a more fundamental issue with this: you are using the old, deprecated mysql_* functions. Those functions are an old, procedural interface to MySQL and don't support the modern features of that RDBMS. I suggest using mysqli or PDO for an OOP approach to database access.
If you are going to stick to this ancient code, you should at least use mysql_real_escape_string() instead of mysql_escape_string().

Categories