I am coding a "social media site" for a class project, and I am having trouble in one section.
When first registering an account, the user must enter a username and password, and click a submit button. PHP code checks the inputs to make sure they're all valid and that there will not be any duplicates, and if everything passes, it adds in the username and password into a SQL table called "users". Users has 3 columns: username, password, and userID. userID is the primary key.
Once that process is completed, we redirect to a separate page, where the user can enter more personal information, such as first and last name, city, country, etc. This table, called "userInfo" has the columns: firstName, lastName, emailAddress, address, city, country, and userID. userID, once again, is the primary key.
What I'm trying to figure out is how to match the two user ID's in an insert statement. I have a form that gathers all the required information, but I am not sure how to set up the SQL query to make sure that users.userID matches userInfo.userID.
Here's my PHP for users (initial registration)
<?php
session_start();
require_once('dbConnect.php');
$error = "false";
$errorMessage = "";
if(isset($_POST['submit'])){
// Get inputs
$username = $_POST['user'];
$password = $_POST['password'];
// Clean inputs and encrypt password
$username = mysqli_real_escape_string($conn, $username);
$password = mysqli_real_escape_string($conn, $password);
$password = md5($password);
// Check username not empty
if (empty($username)) {
$error = "true";
$errorMessage = "Please enter a value for your username";
}
// Check username does not already exist
$checkUserQuery = "SELECT username FROM users WHERE username = '$username'";
$checkResult = $conn->query($checkUserQuery);
if($checkResult->num_rows > 0) {
$error = "true";
$errorMessage = "This username already exists";
}
// Username does not exist, add to database
else {
$insertUserQuery = "INSERT INTO users (username, password) VALUES('$username', '$password')";
$insertResult = $conn->query($insertUserQuery);
$_SESSION['username'] = $username;
header("Location: userInfo.php");
}
}
?>
Here's my PHP code so far for userInfo:
<?php
session_start();
require_once('dbConnect.php');
$error = "false";
$errorMessage = "";
$username = $_SESSION['username'];
if(isset($_POST['submit'])){
// Get inputs
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$emailAddress = "fakeEmailAddress#fakeyfakefake.com";
$address = $_POST['address'];
$city = $_POST['city'];
$country = $_POST['country'];
// Clean inputs
$firstName = mysqli_real_escape_string($conn, $firstName);
$lastName = mysqli_real_escape_string($conn, $lastName);
$address = mysqli_real_escape_string($conn, $address);
$city = mysqli_real_escape_string($conn, $city);
$country = mysqli_real_escape_string($conn, $country);
// Validate Inputs (Only validating first and last name, location entries are not required)
if(empty($firstName) || empty($lastName)) {
$error = "true";
$errorMessage = "Please enter your first AND last name";
}
else {
}
}
?>
Apologies if this is super messy. Databases are NOT my strong suit lol.
Many thanks to anyone who can help!
You'll want to get the mysqli_insert_id for your insert into the users table and pass that along (potentially via your $_SESSION) for creation in userInfo.
Related
I am building a website's login page for an assignment. When I hash the password in the file that checks the users details it doesn't match with the stored hashed password in the database. The code always goes to the last else statement and relinks me to the login page with the wrong password sv equal to 1. If I don't hash the password, then copy and paste the hashed password from the database into the login form the login works. If anyone can help this would be greatly appreciated
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$email = $_POST["email"];
$pass1 = $_POST["pass"];
$pass = hash('sha256', $pass1);
if(isset($_SESSION['user_type']))
{
unset($_SESSION['user_type']);
}
include("group_detail.php");
$query = "SELECT * from employee WHERE email = '$email' AND password = '$pass'";
$result_employee = $db->query($query);
$employee_row = mysqli_fetch_assoc($result_employee);
if(!empty($employee_row)){
$_SESSION['id'] = $employee_row['employee_ID'];
$_SESSION['name'] = $employee_row['name'];
$_SESSION['user_type'] = $employee_row['title'];
header('Location: homepage.html');
}else{
$query = "SELECT * from customer WHERE email = '$email' AND password = '$pass'";
$result_customer = $db->query($query);
$customer_row = mysqli_fetch_assoc($result_customer);
if(!empty($customer_row)){
$_SESSION['id'] = $customer_row['customer_ID'];
$_SESSION['name'] = $customer_row['name'];
$_SESSION['user_type'] = 'Customer';
$_SESSION['email'] = $customer_row['email'];
header('Location: homepage.html');
}
else{
$_SESSION['wrong_password'] = 1;
header('Location: login.php');
}
}
The registration code
<<?php
// this code checks all reuired fields are filled in appropriately
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$nameErr = $phoneErr = $emailErr = $passwordErr = "";
$name = $address = $eircode = $email = $password = $phone = "";
$employee_ID = 0;
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo $nameErr;
if (empty($_POST["name"])) {
$nameErr = "Your name is required for registration";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and a space allowed";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Your phone number is required for registration";
} else {
$phone = test_input($_POST["phone"]);
}
if(empty($_POST['email']))
{
$emailErr = "Your Email is required for registration";
} else {
include ("group_detail.php");
$email_test = test_input($_POST["email"]);
$sql = "SELECT * from customer WHERE email = '$email_test'";
// Checks if another account uses this email
$result = $db->query($sql); // runs the query
$num_rows_3= mysqli_num_rows($result); // counts how many rows the query applies to
if($num_rows_3 == 0){
// Sets email value if no one else has used this email to sign up before
$email = test_input($_POST["email"]);
}
else{
// Lets the customer know this email is already in use
$emailErr = "Another account has previously been registered with this email. If this is you, you can login ";
}
}
if(empty($_POST['pass1']))
{
$passwordErr = "Password required";
} else {
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
if($pass1 == $pass2){
$pass = hash('sha256',$pass1);
// $pass = $pass1;
} else{
$passwordErr = "The passwords you enter must match";
}
}
if(empty($_POST['address']))
{
$address = "";
}else{
$address = test_input($_POST['address']);
}
if(empty($_POST['eircode']))
{
$eircode = "";
}else{
$eircode = test_input($_POST['eircode']);
}
if ($phoneErr == "" && $nameErr == "" && $passwordErr == "" && $emailErr == "")
{
// This code enters the data from the form into the customer table
include ("group_detail.php");
$q = "INSERT INTO customer(";
$q .= "name, phone, password, email, address, eircode";
$q .= ") VALUES (";
$q .= "'$name', '$phone', '$pass', '$email', '$address', '$eircode')";
$result = $db->query($q);
$sql = "SELECT customer_ID FROM customer ORDER BY customer_ID DESC LIMIT 1";
$result1 = $db->query($sql);
$row = mysqli_fetch_assoc($result1);
$_SESSION['customer'] = $row['customer_ID'];
header('Location: homepage.html');
}
}
?>
Solution
Your field is of the incorrect length. When you use the SHA256 hash function you get an output similar to:
ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f // password123
If you're password field is only 15 characters then the saved value will be truncated:
ef92b778bafe771
However, during the comparison the full value from the logon script is used against the truncated version stored in the DB and therefore there is no match. Because, as you can see above, they aren't the same.
To fix you need to ALTER the table so that the field is at least varchar(64). Then new accounts will work as expected (note: old hashes still won't work - they need to be redone!)
Additional information
There are a few other issues with your code...
You shouldn't be putting variables directly into your code. Instead it is preferred to use a Prepared Statement with parametrised queries where you bind the variables later.
Which basically means in the query we use a place holder ? where we want a variable and then bind variables to the place holders later on
This is mainly to prevent SQL injection and protect you from incorrect input
It is best to use the PHP built in functions password_* to hash and verify passwords.
It's more secure than simply using hash
salts are auto-generated which protects you from things like rainbow tables
The default algorithm for password_hash requires a field length of 60+ characters
There's no need to store excess data in SESSION
The data is already stored in the DB so just fetch it as and when needed
It seems that you have one table for customers and another for employees
This isn't a good design there should be one table for users and then you can set flags for employee, customer, supplier etc.
Your test_input function carries out functions that are usually done on display not on save.
Below is a quick re-write that addresses some of the above (note: the below code is not complete it doesn't, for example, carry out all of the same validation - e.g. checking for illegal characters - it's just for illustrative purposes)
Register
<?php
ini_set('display_errors', true);
ini_set('log_errors', true);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$errors = [];
$name = $_POST["name"] ?? null;
$phone = $_POST["phone"] ?? null;
$email = $_POST['email'] ?? null;
$address = $_POST['address'] ?? null;
$eircode = $_POST['eircode'] ?? null;
$pass1 = $_POST['pass1'] ?? null;
$pass2 = $_POST['pass2'] ?? null;
// Check passwords are the same and assign hash to $pass
$pass = $pass1 === $pass2 ? password_hash($pass1, PASSWORD_DEFAULT) : null;
// Check the required fields are present and not empty
if (!$name || !$phone || !$email || !$pass) {
$errors[] = "Required fields are missing.";
}
// Check if the email address already exists in the DB
$checkEmailExistsSQL = "SELECT COUNT(*) as countEmails FROM user WHERE email = ?";
$checkEmailExistsQuery = $mysqli->prepare($checkEmailExistsSQL);
$checkEmailExistsQuery->bind_param("s", $email);
$checkEmailExistsQuery->execute();
$emailExists = $checkEmailExistsQuery->get_result()->fetch_assoc()["countEmails"];
if ($emailExists !== 0) {
$errors[] = "The email address already exists in the DB";
}
// Check if there were errors and output them; then exit the script
if (count($errors)) {
foreach($errors as $error) {
echo $error, PHP_EOL;
}
exit;
}
include("group_detail.php");
$insertSQL = "
INSERT INTO user
(name, phone, password, email, address, eircode)
VALUES
(?, ?, ?, ?, ?, ?)
";
$insertQuery = $mysqli->prepare($insertSQL);
$insertQuery->bind_param("ssssss", $name, $phone, $pass, $email, $address, $eircode);
$insertQuery->execute();
// Success the user is registered
Logon
<?php
ini_set('display_errors', true);
ini_set('log_errors', true);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$email = $_POST["email"] ?? null;
$pass = $_POST["pass"] ?? null;
// You can remove the old user id. But you don't need to
//
// There's no need to store excess data on the user in
// the SESSION super global; any data that you need
// access to can be retrieved from the DB at will.
// Copying data into SESSION only eats into memory.
unset($_SESSION["id"]);
// Check that something was submitted for email and password
if (!$email || !$pass) {
echo "Error: all fields need to be completed";
exit;
}
include("group_detail.php");
$sql = "SELECT id, password FROM user WHERE email = ?";
$query = $mysqli->prepare($sql);
$query->bind_param("s", $email);
$query->execute();
// Check to see if the email address is registered.
// Then check to see if the password is a match.
if (
!($user = $query->get_result()->fetch_assoc())
|| !password_verify($pass, $user["password"])
) {
echo "Error: the email address or password isn't correct";
exit;
}
// Success the user is logged on
//
$_SESSION["id"] = $user["id"];
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
This time i am trying to make a last seen on user profiles. I've added a column called lastseen in my phpmyadmin with type "DATETIME". When a user logs out, the lastseen should update to the date and hour it currently is. So i made an SQL in my logout script that updates this value. When i tested it, it was not working as always.. Tried many things but none are helping. I figured out that without my WHERE statement the date just updates as it should, but sadly for all users. So the WHERE statement is required in the SQL. And i added it back after testing without it but it's not working again, wich makes me sure its something with WHERE but i really don't see what.
This is my logout script:
<?php
session_start();
session_unset(); // Well.. One of these two will definitely work!
session_destroy();
// Updating
include('C:\xampp2\htdocs\settings\sh_config.php');
include('./static/index/scripts/session_start.php');
$conn = mysqli_connect($database['host'], $database['user'], $database['password'], $database['db'], $database['port']);
$last_timestamp = date("Y-m-d H:i:s");
$last_user = $_SESSION['username'];
$lastseen_query = mysqli_query($conn, "UPDATE users SET lastseen='$last_timestamp' WHERE username = '$last_user'");
header('Location: /');
$conn->close();
?>
The include of "sh_config.php" is private, but i will tell what it does in this script. Well simple answer: i configured the database connection in that file. So everything with $database is configured correctly in that file.
The script of the "session_start.php":
<?php
include('C:\xampp2\htdocs\settings\sh_config.php');
session_start();
// Initializing variables
$username = "";
$email = "";
$errors = array();
// Connect to the database
$db = mysqli_connect($database['host'], $database['user'], $database['password'], $database['db'], $database['port']);
// REGISTER USER
if (isset($_POST['reg_user'])) {
// Receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
$fname = mysqli_real_escape_string($db, $_POST['fname']);
$lname = mysqli_real_escape_string($db, $_POST['lname']);
$sex = mysqli_real_escape_string ($db, $_POST["sex"]);
$bday = mysqli_real_escape_string($db, $_POST['bday']);
// Form validation: ensure that the form is correctly filled ...
// By adding (array_push()) corresponding error unto $errors array
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if (empty($fname)) { array_push($errors, "Firstname is required"); }
if (empty($lname)) { array_push($errors, "Lastname is required"); }
if (empty($sex)) { array_push($errors, "What is your gender?"); }
if (empty($bday)) { array_push($errors, "When is your cakeday?"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// First check the database to make sure
// A user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM users WHERE username='$username' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) { // If user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "Email already exists");
}
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1); // Encrypt the password before saving in the database
$user_ip = $_SERVER['REMOTE_ADDR']; // Getting the IP of the user
$bio = $config['default-bio']; // Setting default biography
$profileimg = $config['default-profileimg']; // Setting default profile image
$timestamp = date('d.m.Y'); // Defining the current date
$query = "INSERT INTO users (username, bio, profileimg, regdate, email, password, firstname, lastname, gender, birthday, ip)
VALUES('$username', '$bio', '$profileimg', '$timestamp', '$email', '$password', '$fname', '$lname', '$sex', '$bday', '$user_ip')";
mysqli_query($db, $query);
session_regenerate_id();
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = TRUE;
$_SESSION['success'] = "You are now logged in";
// Generate user id
$generate_id_query = "SELECT id FROM users WHERE username='$username' ORDER BY id";
$get_id = $db->query($generate_id_query);
$gen_id = $get_id->fetch_assoc();
if ($gen_id['id'] <= 0) { // Checking if the user id is a valid id (not below or equal to 0), and if not, displaying a critical error
array_push($errors, "Something went wrong whilst signing up, please refer to the helpcenter. (SE100)");
}
if ($get_id->num_rows > 0 && $gen_id['id'] > 0) { // Redirecting the user to his or her profile if it is a valid id
header('location: /content/users/profile?id=' . $gen_id['id'] . '');
}
}
}
// ...
// LOGIN USER
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($username)) {
array_push($errors, "Username or email is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE ( username='$username' OR email = '$username' ) AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
session_regenerate_id();
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = TRUE;
$_SESSION['success'] = "You are now logged in";
// Get user id
$get_id_query = "SELECT id FROM users WHERE username='$username' ORDER BY id";
$get_id = $db->query($get_id_query);
$user_id = $get_id->fetch_assoc();
if ($user_id['id'] <= 0) { // Checking if the user id is a valid id (not below or equal to 0), and if not, displaying a critical error
array_push($errors, "Something went wrong whilst logging in, please refer to the helpcenter. (SE100)");
}
if ($get_id->num_rows > 0 && $user_id['id'] > 0) { // Redirecting the user to his or her feed if it is a valid id
header('location: /content/users/profile?id=' . $user_id['id'] . '');
}
}else {
array_push($errors, "Your credentials do not match our records");
}
}
}
?>
Well, as you see, theres alot of info in it. Basically, this manages everything of registering and logging in and redirecting to the unique profile with the user id. I thought this file might come in handy because the id and username are defined in this file. If you look good, you can see that i included this file to my logout script so the defined words should just work, but they don't. Trying to redefine it in the file without the include, doesn't work either. Oh by the way, i use MySQLi.
Help me out please, thanks already.
You have a bug in your code, in that when a user logs in with their email address that address is stored in $_SESSION['username']. In your log out script you assume that that is in fact their username where in reality it might not be. Change your update query to something like this and your problem might be solved:
UPDATE users
SET lastseen='$last_timestamp'
WHERE username = '$last_user'
OR email = '$last_user';
While this might work I would recommend making use of your precious user id. Instead of comparing strings, which are susceptible to various kinds of errors (letters with wrong case, leading/trailing white space, different encoding, etc.), compare your IDs. This not only makes things less error-prone but will also cut down your computation time, especially in the context of database lookups.
$_SESSION['user_id'] = $user_id['id']; // or $gen_id['id'] in the signup code.
$last_user = $_SESSION['user_id'];
$lastseen_query = mysqli_query($conn, "UPDATE users SET lastseen='$last_timestamp' WHERE id = '$last_user'");
To debug issues like this yourself in the future you can utilize a popular, quick-and-dirty way of dumping the contents of a variable: Print/echo the values of $username and $email when you create a user and echo the value of $username that is used in the above script to update the last seen value in the database like this:
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
var_dump($username);
var_dump($email);
$last_user = $_SESSION['username'];
var_dump($last_user);
If the dump of $last_user matches $email you know that the above bug applies and is the reason why your script(s) misbehave. You might also find there is some issue with the string values (maybe an unintended mutation at some point) which causes the comparison in your SQL query to fail.
I have two pages of form for the sign up process. Both forms feed into two different tables. users and user_profile. I am looking into using $_SESSIONS to pass a unique attribute from the first page to the second so that that there will be a relationship for each user on both tables. The ID column is incremental so i decided to use the username column because it is unique. Now i am having difficulty passing the username from the first page unto the second page so that i can add it to the insert statement for the sql. My code on the first page is as follows
<?php
session_start();
$_SESSION['message'] = '';
$_SESSION['var_user'] = 'username';
....
username is the name of the field from the formand on the second page, i have
<?php
session_start();
$_SESSION['message'] = '';
$username = $_SESSION['var_user'];
$mysqli = new mysqli("localhost", "root", "", "webdev");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$houseno = ($_POST['str_number']);
$street =($_POST['str_name']);
$city = ($_POST['city']);
$county = ($_POST['county']);
$postcode = ($_POST['pst_code']);
$skills = ($_POST['skills']);
$_username = ($_POST[$username]);
$sql = ("INSERT INTO users_profile (house_no, street_name, city, county,
postcode, about_me, username) VALUES ('$houseno', '$street', '$city',
'$county', '$postcode', '$skills', '$_username')");
if ($mysqli->query($sql) === true){
$_SESSION['message'] = "Registration succesful! Added $username to the database!";
header("location: index.html");
} else{
$_SESSION['message'] = 'Registration Unsuccessful, Please login and update your information';
}
}
I have tried everything from using hidden input in the form. Doesn't seem to be working. Any help will be appreciated.
You're using $username as an key on the second page:
$username = $_SESSION['var_user'];
...
$_username = ($_POST[$username]);
Instead you should simply define it on the first page:
$_SESSION['var_user'] = $_POST['var_user']
And use it on the second page:
$username = $_SESSION['var_user'];
I have made a registration PHP file that runs through an authentication and connects to my database that I made in phpMyAdmin. The problem is, I can put in the same username without consequence and it adds to the database, so I could put; dogs as the username and then again put the same.
How can I make it so the user is told; that username already exists choose another one.
Here's my php so far;
Also please tell me where to insert it.
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['username'])) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysql_real_escape_string($username);
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
$password = stripslashes($password);
$password = mysql_real_escape_string($password);
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query($query);
if ($result) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
} else {
?>
You should query the database before inserting any record (user) to users table.
Try the code below:
<?php
$username = mysql_real_escape_string( $username ); //Sql injection prevention
$existance = mysql_query("SELECT username FROM users WHERE username = '" . $username . "'");
if( !$existance ){
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysql_query( $query );
if ( $result ) {
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
else{
//unsuccessful insertion
}
} else {
//the user existed already, choose another username
}
?>
Create an if-statement where you check if $username exists in the db. If it does, throw an error. If not, continue with the code.
Note
Your code is vulnerable to SQL-injection. Read this post: How can I prevent SQL injection in PHP?
Rewriting my entire answer to a working example. I'm going to assume your post variables are the same as mine: email, password, username
<?php
$errorMessage = "";
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
$email = $_POST['email'];
$password = $_POST['password'];
$username = $_POST['username'];
$email1 = $_POST['email'];
$username1 = $_POST['username'];
$password1 = $_POST['password'];
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
$username = htmlspecialchars($username);
$connect = mysql_connect("localhost","DBuser", "DBpassword");
if (!$connect) {
die(mysql_error());
}
mysql_select_db("DBName");
$results = mysql_query("SELECT * FROM users WHERE username = '$username'");
while($row = mysql_fetch_array($results)) {
$kudots = $row['username']; }
if ($kudots != ""){
$errorMessage = "Username Already Taken";
$doNothing = 1;
}
$result = mysql_query("SELECT * FROM users WHERE email = '$email'");
while($row2 = mysql_fetch_array($results)) {
$kudots2 = $row2['email']; }
if ($kudots2 != ""){
$errorMessage = "Email Already in use";
$doNothing = 1;
}
//test to see if $errorMessage is blank
//if it is, then we can go ahead with the rest of the code
//if it's not, we can display the error
if ($errorMessage == "") {
$user_name = "DBUsername";
$pass_word = "DBPassword";
$database = "DBName";
$server = "localhost";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$email = quote_smart($email, $db_handle);
$password = quote_smart($password, $db_handle);
$username = quote_smart($username, $db_handle);
if ($username1 == ""){
$errorMessage = "You need a username";
}
if ($password1 == ""){
$errorMessage = $errorMessage . "<br>You need a password.";
}
if (!(isset($_POST['email']))){
$errorMessage = $errorMessage . "<br>You need an email.";
}
$SQL = "SELECT * FROM users WHERE email = $email";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "email already exists";
$doNothing = 1;
}
if ($errorMessage == "") {
$SQL = "INSERT INTO users (email, username, password) VALUES ($email, $username, $password)";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['email'] = "$email1";
$_SESSION['password'] = "$password1";
header ("Location: myaccount.php");
else {
$errorMessage = "Database Not Found";
}
}
OK, now echo $errorMessage right below or above the form, to inform the user that the Email, or Username is taken. I'm pretty sure I have a duplicate function in here for the Email, but this code does work; disregard if somebody says it's vulnerable to SQL injection; this is a working EXAMPLE! If you want to do MySQL real escape string, just Google it. I had to rewrite a couple things because I don't want my full code on a public board, if for some odd reason this doesn't work; send me an eMail(canadezo121#gmail.com) and I'll send you the full page code. (Which WORKS!) This code will probably raise some concerns with other more professional coders, this example gives you a good logical viewpoint of what goes on and how it works. You can adjust it to MySQLi, PDO, etc as you get more familiar with PHP and MySQL.
1 you must verify if the username all ready exists in database (Select)
2 if not exists after you can insert the new user
I've been trying to mess around with a registration system. However when I try to insert the information into the database. no new row is generated. I'm not getting any errors, and my code seems legitimate. Is there something that I don't know about INSERT INTO?
$username = $_POST['regusername'];
$email = $_POST['regemail'];
$password = $_POST['regpassword'];
$cpassword = $_POST['regpasswordcon'];
$firstname = $_POST['regfirstname'];
$lastname = $_POST['reglastname'];
//check username for weird symbols
if (preg_match('/[\'^£$%&*()}{##~?><>,|=_+¬-]/', $username)){
// one or more of the 'special characters' found in string
//header("Location: /register.php");
echo "Your username should only contain letters and numbers";
exit;
}
//check if username is taken
$check = $con->prepare("SELECT * FROM accounts WHERE username=:user");
$check->bindParam(':user',$username);
$check->execute();
$result = $check->fetch(PDO::FETCH_ASSOC);
if(!empty($result)){
//header("Location: /register-page.php"); //direct browser back to sign in
echo "User is already taken";
exit;
}else{ //otherwise proceed to register new user
//Hashing of password
$hpassword = password_hash($password, PASSWORD_DEFAULT);
//Prepared statements for SQL injection prevention
$query = $con->prepare("INSERT INTO accounts (username, password, email, firstname, lastname) VALUES (:name,:hpassword,:email,:fname,:lname) ");
//bind parameters
$query->bindParam(':name',$username);
$query->bindParam(':hpassword',$hpassword);
$query->bindParam(':email',$email);
$query->bindParam(':fname',$firstname);
$query->bindParam(':lname',$lastname);
$query->execute();
}