I am trying to make a registration form in which I have connected to the database and it can also check whether the username is unique or not but unfortunately, I can't insert the new data in my table.
I would really appreciate if anyone could help me with this.
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include 'connect.inc.php';
if(isset($_POST['submit'])) {
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$password2 = mysql_real_escape_string($_POST['password2']);
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
//md5 password
$password_hash = md5($password);
//check to see if the fields are empty
if(empty($username) || empty($password)|| empty($firstname)|| empty($lastname)) {
echo "Not all fields filled!<br /><br />";
exit();
}
//check if password is equal
if($password != $password2) {
echo "Your Passwords Do Not Match.<br />";
exit();
} else {
$query = "SELECT `username` From `users` WHERE username='$username'";
$result = mysql_query($query);
if(mysql_num_rows($result) ==1) {
echo "Sorry, that user has already exists.";
exit();
} else {
$query1= mysql_query("INSERT INTO `users` ('',username,password,firstname,lastname) VALUES ('','$username', '$password_hash', '$firstname', '$lastname'");
if($result1 = mysql_query($query1)) {
echo "Registered Successfully";
} else {
echo "Sorry, You could not Register";
}
}
}
}
?>
<form action="" method="POST">
Username:<br />
<input type="text" name="username" /><br /><br />
Password:<br />
<input type="password" name="password" /><br /><br />
Confirm Password:<br />
<input type="password" name="password2" /><br /><br />
First Name:<br />
<input type="text" name="firstname" /><br /><br />
Last Name:<br />
<input type="text" name="lastname" /><br /><br />
<input type="submit" value="Register" name="submit" />
</form>
Your INSERT statement is missing a closing parenthesis.
$query1= mysql_query("INSERT INTO ... '$lastname'");
$query1= mysql_query("INSERT INTO ... '$lastname')");
^
By the way, I find it easier when doing a single-row INSERT to use an alternative syntax, so the column names and the value are matched up:
$query1= mysql_query("INSERT INTO `users` SET
username='$username',
password='$password',
firstname='$firstname',
lastname='$lastname'");
That's easier to make sure you have the columns matched up to the right variables. Also there's no closing parenthesis to worry about.
See http://dev.mysql.com/doc/refman/5.7/en/insert.html for details on this syntax.
You should also abandon the deprecated mysql extension, and use PDO instead. Read this nice tutorial: https://phpdelusions.net/pdo
And Jay Blanchard is correct that your code is insecure. Security, like correctness, is not an add-on feature. You mention you are a beginner, but you should not start developing bad habits. Read https://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/
Try using
$query1= mysql_query("INSERT INTO users (username,password,firstname,lastname) VALUES ('$username', '$password_hash', '$firstname', '$lastname'");
Replace your else block with
else {
die('Error: ' . mysql_error());
//echo "Sorry, You could not Register";
}
From your comment, your INSERT QUERY is wrong. To find out what is wrong with your SQL query, add var_export($query1, true) with die. i.e.
die('Error: ' . mysql_error().'<br>Info: '.var_export($query1, true));
My guess is that you are still using your old query which has '' as one of the column names.
You want to probably insert the user id in the database.Define it as Autoincrement e remove the blank data from the query below:
Before:
$query1= mysql_query("INSERT INTO `users` ('',username,password,firstname,lastname) VALUES ('','$username', '$password_hash', '$firstname', '$lastname'");
After:
$query1= mysql_query("INSERT INTO `users` (username,password,firstname,lastname) VALUES ('$username', '$password_hash', '$firstname', '$lastname')") or die(mysql_error());
And you need also to replace the line with the code if($result1 = mysql_query($query1)) { by if($result1) {
Related
I'm trying to create a very basic registration and login system in PHP. I am very new to this, so I followed a video on YouTube. I'm guessing my problem is that I'm using some function that may have been depreciated in PHP 7. I have included the code I have below. What should I correct? I know I don't have much error handling or such yet. I just want to get the basics down and create a page where the user can register, login, and then have their user id or name displayed on the page. I got that part to work, but nothing shows up in the database when I log in. Also, how do you get the host name? I'm using a webhosting service, and not working locally. Thank you for your help!
dbh.php:
<?php
$conn = mysqli_connect("localhost", "usernamehere", "passwordhere",
"mylogindatabase");
if(!$conn)
{
die("Connection failed: ".mysqli_connect_error());
}
?>
welcome.php:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8>
<title>Title</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<form action="login.php" method="POST">
<input type="text" name="uid" placeholder="Username">
<br />
<input type="password" name="pwd" placeholder="Password">
<br />
<button type="submit">LOGIN</button>
</form>
<?php
if(isset($_SESSION['id']))
{echo $_SESSION['id'];}
else{
echo "You are not logged in!";
}
?>
<br />
<br />
<br />
<form action="signup.php" method="POST">
<input type="text" name="first" placeholder="First Name">
<br />
<input type="text" name="last" placeholder="Last Name">
<br />
<input type="text" name="uid" placeholder="Username">
<br />
<input type="password" name="pwd" placeholder="Password">
<br />
<button type="submit">SIGN UP</button>
</form>
<br />
<br />
<br />
<form action="logout.php">
<button>Log Out</button>
</form>
</body>
</html>
signup.php:
<?php
session_start();
include 'dbh.php';
$first = $_POST['first'];
$last = $_POST['last'];
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
echo $first;
echo $last;
echo $uid;
echo $pwd;
$sql = "INSERT INTO user (first, last, uid, pwd)
VALUES ('$first, $last, $uid, $pwd')";
$result = $conn->query($sql);
header("Location: welcome.php");
?>
login.php:
<?php
session_start();
include 'dbh.php';
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
echo $first;
echo $last;
echo $uid;
echo $pwd;
$sql = "SELECT * FROM user WHERE uid='$uid' AND
pwd='$pwd'";
$result = $conn->query($sql);
if(!$row = $result->fetch_assoc())
{
echo "Your username or password is incorrect!";
} else{
$_SESSION['id'] = $row['id'];
}
header("Location: welcome.php");
?>
logout.php:
<?php
session_start();
session_destroy();
header("Location: welcome.php")
?>
Your insert query should be like this :
$sql = "INSERT INTO user (first, last, uid, pwd)
VALUES ('$first', '$last', '$uid', '$pwd')";
Read this for host : http://php.net/manual/en/function.gethostname.php
EDIT: While this will work and will execute correctly, be warned that
your application will be vulnerable to SQL injection attacks without
the proper countermeasures, so when using MySQLi try to use prepared
statements instead of concatenated queries as they are vulnerable
against SQL injection. This might seem complicated and tedious at
first for beginners, but it is very necessary to keep your application
secure. You can use either prepared statements which are preferable or
simply escape the variables (less secure)
Read more here:
http://php.net/manual/en/mysqli.prepare.php
http://php.net/manual/en/mysqli.real-escape-string.php
you have small error in your sql query
$sql = "INSERT INTO user (first, last, uid, pwd)
VALUES ('$first', '$last', '$uid', '$pwd')";
learn more about sql inset query at
http://www.w3schools.com/sql/sql_insert.asp
You have typo mistake in your code. You forgot quotes in your query
So instead of this
$sql = "INSERT INTO user (first, last, uid, pwd)
VALUES ('$first, $last, $uid, $pwd')";
use this
$sql = "INSERT INTO user (first, last, uid, pwd)
VALUES ('$first', '$last', '$uid', '$pwd')";
Also,if you want to explore more then you can see this docs
Maybe you forget in :
$sql = "INSERT INTO user (first, last, uid, pwd)
VALUES ('$first, $last, $uid, $pwd')";
Your query should be:
$sql = "INSERT INTO user (first, last, uid, pwd)
VALUES ('$first', '$last', '$uid', '$pwd')";
If you need the example of how to create login multiuser, read more:
Detailed Technology Center
<?php
include ("db.php");
if (isset($_POST['register'])) {
echo $name = ($_POST["name"]);
echo $email = ($_POST["email"]);
echo $uname = ($_POST["uname"]);
echo $password = ($_POST["pass"]);
$result = mysql_query($con,'SELECT * from company_profile where user_name = "'.$uname.'" or email = "'.$email.'"');
if(mysql_num_rows($result) > 0){
echo "Username or email already exists.";
}else{
$query = mysql_query($con,"INSERT INTO company_profile(user_name, password, company_name, email, phone, country, activation_string) VALUES ('$uname','$password','$name','$email','','','')");
if($query){
echo "data are inserted succesfully.";
}else{
echo "failed to insert data.";
}
}
}
?>
HTML form
<form action="register.php" method="post" id="reg" onsubmit='return validate();'>
Company Name:
<input type="text" class="inputs" name="name" id="name" /><br />
Email:
<input type="text" class="inputs" name="email" id="txtEmail" /><br />
User name:
<input type="text" class="inputs" name="uname" id="uname"/><br />
Password:
<input type="password" class="inputs" name="pass" id="pass1"/><br />
Conferm Password:
<input type="password" class="inputs" name="cpass" id="pass2"/><br /><br />
<input type="submit" value="Register" class="button" />
</form>
Trying to check whether username or email exist in database if yes alert user if no insert values to db. The code doesn't work for me. no error no echo no insertion. any solution?
You have no field with name register
Regarding this
if (isset($_POST['register'])) {
It will never evaluate to true.
<input type="submit" value="Register" class="button" />
needs name attribute name="register"
In addition:
http://php.net/mysql_query
You have wrong order of arguments. However, using mysql_* is highly NOT encouraged. It is an obsolette database API with a lot of vulnerabilities. Switch to mysqli or PDO instead
your first check isset($_POST['register']) is always false because there is no input in your form with the name="register"
and also you chould fix your query , $con should be the second parametre.
and keep in mind that your code is highly vulnerable don't publish this on a server except of your localhost
Try this:-
$result = mysql_query('SELECT * from company_profile where user_name = "'.$uname.'" or email = "'.$email.'"',$con);
mysql_query
as you are using mysql_query, the link identifier should be second paramater
$result = mysql_query('SELECT * from company_profile where user_name = "'.$uname.'" or email = "'.$email.'"', $con);
You are over complicating yourself...
First of all, to check the user, just do this when form submits:
var_dump(mysql_num_rows(mysql_query("select bla bla where username=`{$_GET['username']}`")));
//by bla bla i mean primary key, don't select *, affects performance.
Also, please see this, you have an error in your syntax... take a look at the right parameters for mysql_query
http://ro1.php.net/mysql_query
After you set your queries and do the above test and figure out if its good or not, you can cut the 3-4 lines you have above in 1 if line like this
if(mysql_num_rows(mysql_query("select bla bla where username=`{$_GET['username']}`"))) { //code here
}
Try Without $con in INSERT query
$query = mysql_query("INSERT INTO company_profile
(
user_name, password,
company_name, email,
phone, country,
activation_string
)
VALUES
(
'$uname', '$password',
'$name', '$email',
'', '',
''
)");
You need to specify the name to your input field and check for that:-
<input type="submit" name="register" value="register">
OR
<button type="submit" name="register">Register</buton>
I am using x10hosting.com, I have set up a database and a user for the database, I have also coded the register user page but when I enter all the data and click submit I do not receive any error messages so I am guessing it is connecting to the database just fine but no data is being saved to the tables in the database, here is my code. Any suggestions would be helpful as I have revised my code multiple times now but still nothing has fixed it
<?php
require_once("config.php");
if (!isset($_POST['submit'])) {
?> <!-- The HTML registration form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Please fill the following form to sign up:<br /><br />
Username*: <input type="text" name="username" /><br />
Password*: <input type="password" name="password" /><br />
Password Verify*: <input type="password" name="passwordVeri" /><br />
First name: <input type="text" name="firstName" /><br />
Last name: <input type="text" name="lastName" /><br />
Email*: <input type="type" name="emailAddress" /><br />
Relationship Status*: <input type="type" select name="relationshipStatus" /><br />
<option value="Single">Single</option>
<option value="Taken">Taken</option>
</select>
Country*: <input type="type" name="country" /><br />
City*: <input type="type" name="city" /><br />
Postcode*: <input type="type" name="postCode" /><br />
Mobile number*: <input type="type" name="mobileNumber" /><br />
Gender*: <input type="type" select name="gender" /><br />
<option value="Single">Single</option>
<option value="Taken">Taken</option>
</select>
Date of Birth*: <input type="type" name="dateOfBirth" /> (Format: DD-MM-YYYY)<br />
<input type="submit" name="submit" value="Register" />
</form>
<?php
} else {
## connect mysql server
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
# protect data for insertion
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$emailAddress = mysql_real_escape_string($_POST['emailAddress']);
$firstName = mysql_real_escape_string($_POST['firstName']);
$lastName = mysql_real_escape_string($_POST['lastName']);
$country = mysql_real_escape_string($_POST['country']);
$city = mysql_real_escape_string($_POST['city']);
$relationshipStatus = mysql_real_escape_string($_POST['relationshipStatus']);
$postCode = mysql_real_escape_string($_POST['postCode']);
$mobileNumber = mysql_real_escape_string($_POST['mobileNumber']);
$dateOfBirth = mysql_real_escape_string($_POST['dateOfBirth']);
$gender = mysql_real_escape_string($_POST['gender']);
//set every user to 0
$_POST['accountType'] = 0;
$accountType = mysql_real_escape_string($_POST['accountType']);
//check if the two passwords are identical
if($_POST['password']==$_POST['passwordVeri'])
{
}
else
{
//Otherwise, passwords are not identical
echo "<p>Passwords do not match!</p>";;
}
//We check if the password has 6 or more characters
if(strlen($_POST['password'])>=6)
{
}
else
{
//Otherwise, passwords are not identical
echo "<p>Password must be 6 or more characters!</p>";;
}
//We check if the email form is valid
if(preg_match('#^(([a-z0-9!\#$%&\\\'*+/=?^_`{|}~-]+\.?)*[a-z0-9!\#$%&\\\'*+/=?^_`{|}~-]+)#(([a-z0-9-_]+\.?)*[a-z0-9-_]+)\.[a-z]{2,}$#i',
$_POST['emailAddress']))
{
}
else
{
//Otherwise, email not valid
echo "<p>The email you entered is not valid.!</p>";;
}
# check if username and email exist else insert
$exists = 0;
$result = $mysqli->query("SELECT username from User WHERE username = '{$username}' LIMIT 1");
if ($result->num_rows == 1) {
$exists = 1;
$result = $mysqli->query("SELECT emailAddress from Member WHERE emailAddress = '{$emailAddress}' LIMIT 1");
if ($result->num_rows == 1) $exists = 2;
} else {
$result = $mysqli->query("SELECT emailAddress from Member WHERE emailAddress = '{$emailAddress}' LIMIT 1");
if ($result->num_rows == 1) $exists = 3;
}
if ($exists == 1) echo "<p>Username already exists!</p>";
else if ($exists == 2) echo "<p>Username and Email already exists!</p>";
else if ($exists == 3) echo "<p>Email already exists!</p>";
else {
# insert data into mysql database
$sql = "INSERT INTO `user` (`Userid`, `username`, `password`, `accountType`)
VALUES (NULL, '{$username}', '{$password}', '{$accountType}')";
"INSERT INTO `Member` (`firstName`, `lastName`, `gender`, `emailAddress`, `city`, `country`, `postCode`, `relationshipStatus`, `mobileNumber`)
VALUES (NULL, '{$firstName}', '{$lastName}', '{$gender}', '{$emailAddress}', '{$city}', '{$country}', '{$postCode}', '{$relationshipStatus}', '{$mobileNumber}')";
if ($mysqli->query($sql)) {
//echo "New Record has id ".$mysqli->insert_id;
echo "<p>Registred successfully!</p>";
} else {
echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
exit();
}
}
}
}
?>
Firstly, you're mixing mysql_ with mysqli_ functions.
Also, your INSERT's columns and VALUES do not match. You have 9x columns for your INSERT and 10x VALUES for your Member table (VALUES).
$sql = "INSERT INTO `user` (`Userid`, `username`, `password`, `accountType`)
VALUES (NULL, '{$username}', '{$password}', '{$accountType}')";
"INSERT INTO `Member` (`firstName`, `lastName`, `gender`, `emailAddress`, `city`, `country`, `postCode`, `relationshipStatus`, `mobileNumber`)
VALUES (NULL, '{$firstName}', '{$lastName}', '{$gender}', '{$emailAddress}', '{$city}', '{$country}', '{$postCode}', '{$relationshipStatus}', '{$mobileNumber}')";
Either remove the NULL for your Member query or add the appropriate USER_ID field for it, before firstName. That alone will stop your query from executing.
To use mysqli_real_escape_string, you will need to change what you presently have, to:
# protect data for insertion
$username = mysqli_real_escape_string($mysqli,$_POST['username']);
$password = mysqli_real_escape_string($mysqli,$_POST['password']);
$emailAddress = mysqli_real_escape_string($mysqli,$_POST['emailAddress']);
$firstName = mysqli_real_escape_string($mysqli,$_POST['firstName']);
$lastName = mysqli_real_escape_string($mysqli,$_POST['lastName']);
$country = mysqli_real_escape_string($mysqli,$_POST['country']);
$city = mysqli_real_escape_string($mysqli,$_POST['city']);
$relationshipStatus = mysqli_real_escape_string($mysqli,$_POST['relationshipStatus']);
$postCode = mysqli_real_escape_string($mysqli,$_POST['postCode']);
$mobileNumber = mysqli_real_escape_string($mysqli,$_POST['mobileNumber']);
$dateOfBirth = mysqli_real_escape_string($mysqli,$_POST['dateOfBirth']);
$gender = mysqli_real_escape_string($mysqli,$_POST['gender']);
//set every user to 0
$_POST['accountType'] = 0;
$accountType = mysqli_real_escape_string($mysqli,$_POST['accountType']);
Also, you could do what you did for your first query by doing the following:
$sql2 = "INSERT INTO `Member` (`firstName`, `lastName`, `gender`, `emailAddress`, `city`, `country`, `postCode`, `relationshipStatus`, `mobileNumber`)
VALUES ('{$firstName}', '{$lastName}', '{$gender}', '{$emailAddress}', '{$city}', '{$country}', '{$postCode}', '{$relationshipStatus}', '{$mobileNumber}')";
if ($mysqli->query($sql2)) {
//echo "New Record has id ".$mysqli->insert_id;
echo "<p>Member table updated successfully!</p>";
} else {
echo "<p>MySQL Member table error no {$mysqli->errno} : {$mysqli->error}</p>";
exit();
}
Your code has a problem with brackets:
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
...blablah your entire code...
}
Instead of:
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
...blablah your entire code...
So your code will be never executed. This is the correct version:
<?php
require_once("config.php");
if (!isset($_POST['submit'])) {
?> <!-- The HTML registration form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Please fill the following form to sign up:<br /><br />
Username*: <input type="text" name="username" /><br />
Password*: <input type="password" name="password" /><br />
Password Verify*: <input type="password" name="passwordVeri" /><br />
First name: <input type="text" name="firstName" /><br />
Last name: <input type="text" name="lastName" /><br />
Email*: <input type="type" name="emailAddress" /><br />
Relationship Status*: <input type="type" select name="relationshipStatus" /><br />
<option value="Single">Single</option>
<option value="Taken">Taken</option>
</select>
Country*: <input type="type" name="country" /><br />
City*: <input type="type" name="city" /><br />
Postcode*: <input type="type" name="postCode" /><br />
Mobile number*: <input type="type" name="mobileNumber" /><br />
Gender*: <input type="type" select name="gender" /><br />
<option value="Single">Single</option>
<option value="Taken">Taken</option>
</select>
Date of Birth*: <input type="type" name="dateOfBirth" /> (Format: DD-MM-YYYY)<br />
<input type="submit" name="submit" value="Register" />
</form>
<?php
} else {
## connect mysql server
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
# protect data for insertion
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$emailAddress = mysql_real_escape_string($_POST['emailAddress']);
$firstName = mysql_real_escape_string($_POST['firstName']);
$lastName = mysql_real_escape_string($_POST['lastName']);
$country = mysql_real_escape_string($_POST['country']);
$city = mysql_real_escape_string($_POST['city']);
$relationshipStatus = mysql_real_escape_string($_POST['relationshipStatus']);
$postCode = mysql_real_escape_string($_POST['postCode']);
$mobileNumber = mysql_real_escape_string($_POST['mobileNumber']);
$dateOfBirth = mysql_real_escape_string($_POST['dateOfBirth']);
$gender = mysql_real_escape_string($_POST['gender']);
//set every user to 0
$_POST['accountType'] = 0;
$accountType = mysql_real_escape_string($_POST['accountType']);
//check if the two passwords are identical
if($_POST['password']==$_POST['passwordVeri'])
{
}
else
{
//Otherwise, passwords are not identical
echo "<p>Passwords do not match!</p>";;
}
//We check if the password has 6 or more characters
if(strlen($_POST['password'])>=6)
{
}
else
{
//Otherwise, passwords are not identical
echo "<p>Password must be 6 or more characters!</p>";;
}
//We check if the email form is valid
if(preg_match('#^(([a-z0-9!\#$%&\\\'*+/=?^_`{|}~-]+\.?)*[a-z0-9!\#$%&\\\'*+/=?^_`{|}~-]+)#(([a-z0-9-_]+\.?)*[a-z0-9-_]+)\.[a-z]{2,}$#i',
$_POST['emailAddress']))
{
}
else
{
//Otherwise, email not valid
echo "<p>The email you entered is not valid.!</p>";;
}
# check if username and email exist else insert
$exists = 0;
$result = $mysqli->query("SELECT username from User WHERE username = '{$username}' LIMIT 1");
if ($result->num_rows == 1) {
$exists = 1;
$result = $mysqli->query("SELECT emailAddress from Member WHERE emailAddress = '{$emailAddress}' LIMIT 1");
if ($result->num_rows == 1) $exists = 2;
} else {
$result = $mysqli->query("SELECT emailAddress from Member WHERE emailAddress = '{$emailAddress}' LIMIT 1");
if ($result->num_rows == 1) $exists = 3;
}
if ($exists == 1) echo "<p>Username already exists!</p>";
else if ($exists == 2) echo "<p>Username and Email already exists!</p>";
else if ($exists == 3) echo "<p>Email already exists!</p>";
else {
# insert data into mysql database
$sql = "INSERT INTO `user` (`Userid`, `username`, `password`, `accountType`)
VALUES (NULL, '{$username}', '{$password}', '{$accountType}')";
"INSERT INTO `Member` (`firstName`, `lastName`, `gender`, `emailAddress`, `city`, `country`, `postCode`, `relationshipStatus`, `mobileNumber`)
VALUES (NULL, '{$firstName}', '{$lastName}', '{$gender}', '{$emailAddress}', '{$city}', '{$country}', '{$postCode}', '{$relationshipStatus}', '{$mobileNumber}')";
if ($mysqli->query($sql)) {
//echo "New Record has id ".$mysqli->insert_id;
echo "<p>Registred successfully!</p>";
} else {
echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
exit();
}
}
}
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().
Hey guys i had a similar problem before but i scraped that idea. Now basically my system allows my users to input there data into the fields and if they submit it the information will go to the database. Now for some reason the data does not go and i am presented with the echo that i stored in my else statement which was " echo" try again later" ;"
Now i have gone back into the database and looked at all the fileds and there correct names and placed them into the query but nothing gets stored into the db. Now you may be thinking whats the file on top called connect.inc.php in my code this is its basically a script in php which connects to the server.
here is my code pleas have a look thank you :)
<?php
//require 'core.inc.php';
include 'connect.inc.php';
if(isset($_POST['Username'])&& isset($_POST['Password']) && isset($_POST['PasswordAgain'])&& isset($_POST['Firstname'])&& isset($_POST['Lastname'])){
$username = $_POST['Username'];
$password = $_POST['Password'];
$password_again = $_POST['PasswordAgain'];
$Firstname = $_POST['Firstname'];
$password_hash = md5($password);
$Lastname = $_POST['Lastname'];
if(!empty($username)&& !empty($password) && !empty($password_again) && !empty($Firstname) && !empty($Lastname)){
if ($password !== $password_again) {
echo "passwords do not match";
}
else{
$query = "SELECT username FROM members WHERE username = '$username'";
$query_run = mysql_query($query);
if(mysql_num_rows($query_run )==1){
echo "The username ". $username ." is taken";
}else{
$query = "INSERT INTO members VALUES ('','Firstname','Lastname','Username','Password')";
if ($query_run = mysql_query($query)){
echo "Well done";
}else{
echo "Sorry we couldn't register at this time. Please try again later thank you";
}
}
}
}
else{
echo "Please fill in all the details thank you ";
}
}
?>
<form action="join.inc.php" method="post">
Username: <input type="text" name="Username" value="<?php echo $username; ?>" /><br />
Password: <input type="password" name="Password" /><br />
Password Again: <input type="password" name="PasswordAgain" /><br />
FirstName: <input type="text" name ="Firstname" value="<?php echo $Lastname; ?>" /><br />
LastName: <input type="text" name ="Lastname" value="<?php echo $Firstname ?>" /><br />
<input type="submit" value="SUBMIT" />
</form>
Connect Script
I would recommend explicitly stating the columns used in your INSERT statement.
INSERT INTO members (`field1`, `field2`, ...)
VALUES ('','Firstname','Lastname','Username','Password')
Also, what is the blank value you are trying to insert? If that field is an AUTO_INCREMENT field, you should not include it in the VALUES declaration.
Try this :
INSERT INTO members (`field1`, `field2`, ...)
VALUES ('','$Firstname','$Lastname','$Username','$password_hash')
IF your first field is auto_increment
omit the field1 as shown below
INSERT INTO members (`field2`,`field3`,...)
VALUES ('field2Val','field3Val',...);
password !== $password_again
should be
password != $password_again
enable error_reporting and see whats wrong actually, is the ID first field auto increment?
if that's auto increment your query will execute but if its not auto increment and set to PK only it wont insert records and raise duplicate key error.
hope this helps
Try changing to:
$query = "INSERT INTO members VALUES ('". $Firstname."','". $Lastname. "','" .$username. "','" .$password_hash. "')";
$result = mysql_query($query);
if (!$result){
echo "Sorry we couldn't register at this time. Please try again later thank you";
}else{
echo "Well done";
}
you should use something like this.
$query = "insert into members (id,username) values ('','$username')";