For some reason my last two variables will not input into the database. I am referring to $verifyKey and $keyExpire. Here is my code with comments. I am adding the entire page to make sure I don't have the wrong character somewhere it isn't supposed to be. Effectively this is a registration page that inserts the information into the database and gives a verification key for email verification later.
I have the fields matched up with the code in the database and they are set to longtext and text. I don't want to insert directly as I am trying to get this method to work with all 5 variables.
<?php
// This is not seen by the end user so this file is placed in the unseen folder
// Check if the user used the sign up button
if (isset($_POST['signup-submit'])) {
// uses the database handler
require 'dbh.php';
$username=$_POST['uid'];
$email=$_POST['mail'];
$password=$_POST['pwd'];
$passwordcnfrm=$_POST['pwd-cnfrm'];
$verifyKey=md5(time().$username);
$keyExpire=date("U")+ 86400;
// Checks to see if any field are empty
if(empty($username)||empty($email)||empty($password)||empty($passwordcnfrm)) {
// This header returns the username and/or email address so the user doesn't have to retype it
header("Location:../signup.php?error=emptyfields&uid=".$username."&mail=".$email);
exit();
}
// Checks if both the user and email are invalid
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)&&!preg_match("/^[a-zA-Z0-9]*$/",$username)) {
header("Location:../signup.php?error=invalidmailuid");
exit();
}
// Checks if the email is valid
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location:../signup.php?error=invalidmail&uid=".$username);
exit();
}
// Checks if the username is valid.
else if (!preg_match("/^[a-zA-Z0-9]*$/",$username)) {
header("Location:../signup.php?error=invaliduid&mail=".$email);
exit();
}
// Checks to see if the password and confirm password match
else if ($password !== $passwordcnfrm){
header("Location:../signup.php?error=passwordcheck&uid=".$username."&mail=".$email);
exit();
}
// Checks to see if the username is already in use or password is invalid
else {
$sql = "SELECT uidUsers FROM users WHERE uidUsers=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt,$sql)) {
header("Location:../signup.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt,"s",$username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows();
if ($resultCheck < 0){
header("Location:../signup.php?error=usertaken&mail=".$email);
exit();
}
else {
//Inserts into database
$sql = "INSERT INTO users (uidUsers,emailUsers,pwdUsers,verify,expires) VALUES (?,?,?,?,?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt,$sql)) {
header("Location:../signup.php?error=sqlerror");
exit();
}
else {
$hashedPwd =password_hash($password,PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt,"sssss",$username,$email,$hashedPwd,$verifyKey,$keyExpire);
mysqli_stmt_execute($stmt);
header("Location:../signup.php?signup=success");
}
}
}
}
//Closes session to db
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
else {
header("Location:../signup.php");
}
In description of mysqli_stmt::bind_param there is this criptic note:
If data size of a variable exceeds max. allowed packet size
(max_allowed_packet), you have to specify b in types and use
mysqli_stmt_send_long_data() to send the data in packets.
http://php.net/manual/en/mysqli-stmt.bind-param.php
Practically it means that for every longtext (and blob) field you have to additionally call mysqli_stmt_send_long_data after mysqli_stmt_bind_param. Otherwise you have this strange behavious when everything works ok, but fields are not set.
Related
I am setting up a new website with registration and login forms. As a beginner I am usting mostly part of codes I find online and in books. I have finished registration form and it works perfectly, but now I have a problem with a login form, because all codes that I can find are based on hashed password and the login form I have to build does not need it. Can you help to convert the script I have now into script that will work without any password (instead of a password it just need a 6 digital number which is not hashed).
I tried check_login, but it did not work.
$sql = "SELECT id, email, pin FROM users WHERE email = ?";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("s", $param_email);
// Set parameters
$param_email = $email;
// Attempt to execute the prepared statement
if($stmt->execute()){
// Store result
$stmt->store_result();
// Check if username exists, if yes then verify password
if($stmt->num_rows == 1){
// Bind result variables
$stmt->bind_result($id, $username, $numerpin);
if($stmt->fetch()){
if($stmt->num_rows == 1){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["email"] = $email;
// Redirect user to welcome page
header("location: dashboard.php");
} else{
// Display an error message if password is not valid
$numerpin_err = "The password you entered was not valid.";
}
}
} else{
// Display an error message if username doesn't exist
$email_err = "No account found with that username.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
You have this query:
"SELECT id, email, pin FROM users WHERE email = ?"
You are checking for the email to be correct. You could change it to
"SELECT id, email, pin FROM users WHERE email = ? and pin = ?"
of course, passing pin as well. Also, your error message is misleading:
if($stmt->num_rows == 1){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["email"] = $email;
// Redirect user to welcome page
header("location: dashboard.php");
} else{
// Display an error message if password is not valid
$numerpin_err = "The password you entered was not valid.";
}
what if there are multiple records with the very same email? In that case it will say that password is incorrect, without checking its actual value. It would be much more reliable to get the record(s) by email and pin, loop the results and when a match is found, then create a session. If there is no match, then error.
As others suggested. The best approach is to use hash password but since you do not want that. you can go ahead with this. Try the code below
<?php
$mysqli = new mysqli('localhost', 'your username', 'your password', 'your db name');
if($mysqli->connect_error){
echo "cannot connect to database";
}
// assuming your post variable is set as follows
$email = $_POST['email'];
$pin = $_POST['pin'];
$stmt = $mysqli->prepare("SELECT id, email, pin FROM users WHERE email = ? AND pin = ?");
/* i is for integer and s is for string. I suspect that your pin must be integer so I set the bind to i
*/
$stmt->bind_param("si", $email, $pin);
if($stmt->execute()){
$stmt->store_result();
$result = $stmt->get_result();
$num_rows = $result->num_rows;
}
if($num_rows == 1){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["email"] = $email;
// Redirect user to welcome page
header("location: dashboard.php");
}else{
echo "Error: Either Email or Pin number is wrong";
}
?>
I want to record the user ID from the current logged in user who enters data into the form which in turn is recorded to a database table
At present the insert query is running and updating all but the user id..the user id variable is definitely working as I am able to echo it out without any issues on the same page
Code is as follows;
$barcode = $_POST['barcode'];
$weight = $_POST['weight'];
$userId = $_SESSION['userId'];
//error handling begins
// check for any empty inputs.
if (empty($barcode) || empty($weight)) {
header("Location: ../record.php?error=emptyfields&barcode=".$barcode."&weight=".$weight);
exit();
}
//we check if valid barcode entered. In this case ONLY letters and numbers.
else if (!preg_match("/^[a-zA-Z0-9]*$/", $barcode)) {
header("Location: ../record.php?error=invalidbarcode&barcode=".$weight);
exit();
}
// check for an invalid weight. In this case ONLY numbers.
else if (!preg_match("/^[0-9].*$/", $weight)) {
header("Location: ../record.php?error=invalidweight&barcode=".$barcode);
exit();
}
else {
$sql = "INSERT INTO trimrecords (barcode, weight, createdby) VALUES (?,?,?);";
// initialize a new statement using the connection from the dbh.inc.php file.
$stmt = mysqli_stmt_init($conn);
// prepare SQL statement AND check if there are any errors with it.
if (!mysqli_stmt_prepare($stmt, $sql)) {
// If there is an error send the user back to the record page.
header("Location: ../record.php?error=sqlerror");
exit();
}
else {
// If there is no error continue the script!
// bind the type of parameters we expect to pass into the statement, and bind the data from the user.
mysqli_stmt_bind_param($stmt, "ssi", $barcode, $weight, $userId);
// execute the prepared statement and send it to the database!
// data is registered to Db at this stage
mysqli_stmt_execute($stmt);
// send back with success
header("Location: ../record.php?record=success");
exit();
}
}
Add session_start() to the top and all worked.
The goal is to create profile settings page, where users can change their email address, but before updating ask them to enter their password.
So, I need to fetch password from database and compare it to password entered by user, and if they match update email address.
But, when I try to implement logic, I get a blank page. Code work till query. It stop working when $passwordCheck = true and $resultCheck = 0 (see edited below).
Edited (2019.01.09): redirects work till header('Location: ../edituser.php?success=emailupdate'). When enter new email, correct password and click submit button, it shows changeemail.php (my action script) page instead of redirect to edituser.php with success messsage. I assume that something get broken and script stuck. Also, added complete script.
Edited (2019.01.10): my question is: how to implement password confirmation before updating data using PHP. Above description shows how I tried to implement it. I'm looking for information about solution, different approaches to this problem or some help with my code. Sorry if I not clarify my question detailed enough. I also add profile settings picture below.
Picture 1. Profile settings page
changeemail.php script:
// Check for submit
if (isset($_POST['submit'])) {
// Get form data
$update_id = $_POST['update_id'];
$email = test_input($_POST['email']);
$confirm_password = test_input($_POST['confirm_password']);
// Store post id in session
session_start();
$_SESSION['update_id'] = $update_id;
// Check for empty field
if (empty($email)) {
header('Location: ../edituser.php?error=emptyemail');
exit();
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // Check email
header('Location: ../edituser.php?error=invalidemail');
exit();
} else if (empty($confirm_password)) {
header('Location: ../edituser.php?error=emptyconfirmpassword');
exit();
} else {
// Check if email already exist
$query = "SELECT email, password FROM users WHERE email = ?";
// Create prepared statement
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $query)) {
header('Location: ../edituser.php?error=sqlerror');
exit();
} else {
mysqli_stmt_bind_param($stmt, 's', $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $email, $password);
$resultCheck = mysqli_stmt_num_rows($stmt);
while (mysqli_stmt_fetch($stmt)) {
// Check if passwords match
$passwordCheck = password_verify($confirm_password, $password);
if ($passwordCheck == false) {
header('Location: ../edituser.php?error=wrongconfirmpassword');
exit();
} else if ($passwordCheck == true && $resultCheck > 0) {
header('Location: ../edituser.php?error=emailtaken');
exit();
}
// Update email
$query = "UPDATE users SET email = ? WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $query)) {
header('Location: ../edituser.php?error=sqlerror');
exit();
} else {
mysqli_stmt_bind_param($stmt, 'si', $email, $update_id);
mysqli_stmt_execute($stmt);
header('Location: ../edituser.php?success=emailupdate');
exit();
}
}
}
}
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($conn);
} else {
header('Location: ../edituser.php');
exit();
}
As I said before - check your logic......
Sometimes that is best done in a 'reverse' manner - - - for instance, in this case, you say
When enter new email, correct password and click submit button, it shows changeemail.php (my action script) page instead of redirect to edituser.php with success messsage. I assume that something get broken and script stuck.
So, in other words....
EXPECTED RESULT: redirect to edituser.php
CURRENT RESULT: shows emailupdate (this is not clear in the question, though I believe that this is the case - you are redirecting to edituser.php?success=emailupdate. If this is not the case, clarify! My example below will presume this....)
So, let's follow the logic...... (remove all non-logic and/or redirection code to find why it is hitting where it is....)
First, let's look at why it isn't going where you want......
(EXPECTED RESULT: redirect to edituser.php)
Removing all code except what you expect, we get
// Check for submit
if (isset($_POST['submit'])) {
// DO ALL SORTS OF STUFF
} else {
// NEVER SELECT THIS IF THERE IS A 'SUBMIT' POSTED
header('Location: ../edituser.php');
exit();
}
However, to get to this page, you HAVE a 'submit', so the 'expected' line will NEVER be selected!
Now, let's look at what IS happening - and why......
// Check for submit
if (isset($_POST['submit'])) {
// Get form data
$update_id = $_POST['update_id'];
$email = test_input($_POST['email']);
$confirm_password = test_input($_POST['confirm_password']);
// Check for empty field
if (empty($email)) {
// WE HAVE EMAIL, SO THIS IS NOT HIT
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // Check email
// EMAIL IS OK, SO NOT HIT
} else if (empty($confirm_password)) {
// PASSWORD IS OK, SO NOT HIT
} else {
// EMAIL FOUND SO WE ARE HERE
while (mysqli_stmt_fetch($stmt)) {
// Check if passwords match
$passwordCheck = password_verify($confirm_password, $password);
if ($passwordCheck == false) {
// PASSWORD IS OK, SO NO HIT
} else if ($passwordCheck == true && $resultCheck > 0) {
// OK, SO NO HIT
}
// Update email
$query = "UPDATE users SET email = ? WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $query)) {
// NO FAILED SQL, SO NO HIT
} else {
// NO OTHER LOGIC, SO THIS _WILL_ BE A HIT........
// *****************************************
header('Location: ../edituser.php?success=emailupdate');
exit();
// *****************************************
}
}
}
}
}
Again, it is clear from your code that you will get the results you describe.
What I'm not sure of is really what you are expecting to do (so I can't really recommend code for you), though certainly the logic you are using is taking you where you are telling it to go - even though it is not what you would like to happen.....
You may need an additional check somewhere (to determine if you really need to update the email or just send them to the edituser page, etc.) - though you have to get the logic straight!
Hopefully this will show you a couple ways you can break down the code to get where you are wanting to go. I often START writing code with comments - then go back and fill in the logic with code. This both gives a simple way to follow along with the steps and gives well commented code for later debugging. I highly suggest you use such a system for your coding - certainly when starting out it is useful, but having well commented code will serve you well throughout your life.
To fix my issue I add another query:
$query = "SELECT password FROM users WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $query)) {
header('Location: ../index.php?error=sqlerror');
exit();
} else {
mysqli_stmt_bind_param($stmt, "i", $update_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
Old query won't find password for updated email, because it's not exist yet, and will close connection.
I searched for this question but couldn't find it.
I have made a create user page that will allow the user to create an account on my page using a username. Usernames can be any combination of letters and numbers. When they create the user, it is supposed to call the same page, then redirect the user to the main page when it sees that the session variable is now set.
When I create a user with only letters in the username, it works fine and redirects them to the index page. However, when I create a user such as "student1" it will not set the session variable and therefore not redirect them.
You can try it yourself at http://collinmath.com/accounts/create.php to see what I mean. (Just don't use real info since I haven't set up the SSL yet)
<?php
// call the register() function if register_btn is clicked
if (isset($_POST['register_btn'])) {
// Set variables equal to POST data
$login_name = $_POST['username'];
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$email = $_POST['email'];
$role = $_POST['role'];
$pwd1 = $_POST['password_1'];
$pwd2 = $_POST['password_2'];
register();
}
// Register function will check the input and add the user if
// the input is accepted
function register() {
global $login_name;
global $first_name;
global $last_name;
global $email;
global $role;
global $errors;
global $connection;
global $pwd1;
global $pwd2;
global $hostname;
global $username;
global $password;
global $dbname;
// Connect to database
$connection = mysqli_connect($hostname, $username, $password);
mysqli_select_db($connection, $dbname);
// Check that username contains only letters and number
if (preg_match('/[^A-Za-z0-9]/', $login_name)) {
array_push($errors, "Username must contain only letters and/or numbers");
} else {
$login_name = strtolower($login_name);
}
// Sanitize SQL data
$first_name = mysqli_real_escape_string($connection, $first_name);
$last_name = mysqli_real_escape_string($connection, $last_name);
// Validate registration input and generate error log if there are issues
// Check if username is taken or empty
if (strlen($login_name) > 4) {
$query = "SELECT `User_Login` AS `Login` FROM `CMP_Users` WHERE `User_Login`=?";
$mysqli = new mysqli($hostname, $username, $password, $dbname);
$mysqli->set_charset("utf8");
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $login_name);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ($row[Login]) {
array_push($errors, "That username is taken");
}
} else {
array_push($errors, "Username must be at least 5 characters long");
};
if (strlen($login_name) > 16) {
array_push($errors, "Username must be 16 characters or less");
}
// Check First name
if ($first_name) {
if (preg_match('/[^A-Za-z\'\-\s]/', $first_name) || !preg_match('/[A-Za-z]/i', $first_name)) {
array_push($errors, "First Name is not valid");
}
if (strlen($first_name) > 15) {
array_push($errors, "First name must be 15 characters or less");
}
} else {
array_push($errors, "Must enter a first name");
}
//Check Last name
if ($last_name) {
if (preg_match('/[^A-Za-z\'\-\s]/', $last_name) || !preg_match('/[A-Za-z]/i', $last_name)) {
array_push($errors, "Last Name is not valid");
}
if (strlen($last_name) > 25) {
array_push($errors, "Last name must be 25 characters or less");
}
} else {
array_push($errors, "Must enter a last name");
}
// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
array_push($errors, "Please enter a valid e-mail address");
}
if (strlen($email) > 50) {
array_push($errors, "E-mail address must be 50 characters or less");
}
// Check if role is legal
$role_value = 0;
if ($role == 'student') {
$role_value = 1;
} else if ($role == 'teacher') {
$role_value = 2;
} else {
array_push ($errors, "No role selected");
}
// Check if passwords match
if ($pwd1 != $pwd2) {
array_push($errors, "Passwords do not match");
} else {
// Check if passwords meet criteria
if (!preg_match('/\W/', $pwd1) || !preg_match('/[0-9]/', $pwd1) ||
strlen($pwd1) < 10) {
array_push($errors, "Password is not valid");
}
}
// If there are no errors, commit results to DB and create session
if (empty($errors)) {
// Hash passwords for DB storage
$pwd1 = password_hash($login_name . $_POST['password_1'], PASSWORD_DEFAULT);
/*
THIS WILL NEED TO BE UPDATED WHEN E-MAIL VALIDATION IS IMPLEMENTED
*/
// Create query for inserting new data
$add_user_query = "INSERT INTO `CMP_Users` (User_First_Name, User_Last_Name, "
. "User_Login, User_Email, User_Password, User_Role, User_Created) VALUES "
. "(?, ?, ?, ?, ?, ?, NOW())";
$mysqli_add_user = new mysqli($hostname, $username, $password, $dbname);
$mysqli_add_user->set_charset("utf8");
$stmt_add_user = $mysqli_add_user->prepare($add_user_query);
$stmt_add_user->bind_param("sssssi", $first_name, $last_name, $login_name, $email, $pwd1, $role_value);
$stmt_add_user->execute();
// Set session variables
$_SESSION['username'] = $login_name;
$_SESSION['role'] = $role_value;
$_SESSION['email'] = $email;
$_SESSION['fname'] = $first_name;
$_SESSION['lname'] = $last_name;
$connection->close();
header('Location: http://www.collinmath.com/mathpages/index.php');
exit();
}
// Close db connection
$connection->close();
}
// Check whether the user is already logged in
// and redirect them to the main user page if they are
if (isset($_SESSION['username'])) {
header('Location: http://www.collinmath.com/mathpages/index.php');
exit();
}
?>
UPDATE:
So, I changed a bunch of the code and tinkered with the php.ini file but I'm still having problems. When I look at my cookies, I see the cookie is there. I see the file is created in the sessions folder and that the variables are set in that file, but there is still no session info when I do a var_dump.
My session_save_path and var_dump shows this:
/home/[myname]/sessions/
array(0) { }
and the file that is created in my sessions folder looks like this:
username|s:7:"testerz";role|i:1;email|s:19:"email#email.com";fname|s:4:"First";lname|s:6:"Name";
Problem Fix:
This is work in progress from the long comment discussion and will be updated as we go
From what you've told me the logic process of your situation is impossible.
RE: Your update:
Then if the session is definitely being written then there are three possible options:
1) there is an ini_set() or a directory-local .ini file which is changing the session name so data from one directory is not being recognised in another, as they're looking in different sessions.
2) You have a spelling or casing issue of your $_SESSION keys.
3) session_start() has not been initiated.
Furter debugging and Solution:
Whenever you var_dump your session data, and it's turning up blank; add these lines:
error_log(print_r(session_status()."<BR>",true));
error_log(print_r(session_name()."<BR>",true));
error_log(print_r($_SESSION,true)); //your original output.
Add this code block to both your data-in page (create.php) and the destination page that is failing to show certain sessions.
If the above are always exactly the same (and they may be if , as you say, some data does "work".
Then the answer is that you definitely absolutely have some lines in your code that change the session values. The symptoms look like you've got a screwed up REGEX preg_ function somewhere. Again; use your PHP Error Log to check these things out.
General Fixes:
Quote your array keys; $row[Login] should be `$row['Login']
Use a single MySQLi connection, of a single type
That type should be the Object Orientated approach (->)
Do not use real_escape_string for Object Orientated MySQL connections.
Use Multibyte PHP String functions
Use UTF8mb4 MySQLi connection character sets, and the same in your tables and columns.
Tidy up your code and your logic process, you've made a funtion but the function always runs so it has no benefit being a function - it may as well just be straight code.
Don't use globals
MySQL does not care about new lines so you don't need to concatenate the SQL strings.
Wow, this was the most random reason...
It turns out the problem was my php.ini file, but not for the reason I thought. I had set the session.cookie_domain value to "collinmath.com" but needed to add a period to the beginning of collinmath. I changed the session.cookie_domain value to ".collinmath.com" and it fixed the problem. I have no idea why this worked, but it did.
I´m currently creating a login script in PHP. When a user tries to login <5 times in a short period of time the account get´s temporary locked and the user get´s an email in order to reactivate the account instantly. This is all working fine, the user fails to login, the database is updated and the email is sent. Then when I try to do this very same thing a second time with the second or third email, the database simply doesn't update. The only way to get it to work for the next email is to remove all values created from the first email in the database.
Here is the relevant code for the login php file.
<?php
include_once 'db_connect.php';
include_once 'functions.php';
...
} elseif (login($email, $password, $mysqli) == 2)
$theid = getId($email, $mysqli); /// this is a function that get´s id based on email located in functions.php
if ($stmt = $mysqli->prepare("SELECT emailSent FROM login_attempts WHERE user_id = ? LIMIT 1"))
{
$stmt->bind_param('i', $theid);
$stmt->execute();
$stmt->bind_result($skickat);
$stmt->fetch();
$stmt->close();
if ($skickat == '0') /// email sent
{
$thehash = md5( rand(0,10000) ); /// Just a random md5 hash for reactivation
$emailsent = 1;
if ($insert_stmt = $mysqli->prepare("UPDATE `secure_login`.`login_attempts` SET `ResetHash` = ?, `emailSent` = ? WHERE `login_attempts`.`user_id` = ?")) {
$insert_stmt->bind_param('sss', $thehash, $emailsent, $theid);
if (! $insert_stmt->execute()) {
header('Location: ../error.php?err=Registration failure: INSERT');
exit();
}
}
else {
header('Location: ../error.php?err=Registration failure: INSERT');
exit();
}
else /// alread sent, we already sent email. Show error that decribe email is sent and it´s locked
{
$_SESSION['lgnerror']= '<p class="error">Error 2</p>';
header('Location: ../login.php');
exit();
}
/// Email code starts from here
$_SESSION['lgnerror']= '<p class="error">Error 1</p>';
Here is the getId function located in functions.php
function getId($email, $mysqli)
{
if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE email = ? LIMIT 1"))
{
$stmt->bind_param('i', $email);
$stmt->execute();
$stmt->bind_result($resultat);
$stmt->fetch();
$stmt->close();
return $resultat;
}
else
{
// Could not create a prepared statement
header("Location: ../error.php?err=Database error: cannot prepare statement");
exit();
}
}
Why does the code only work for the first email and not when you try it a second time? I think the error lies somewhere in the code provided above, if needed just comment and I will provide more code.
The code on tests shows $_SESSION['lgnerror'] "error 2" on the 5th+ attempt when it schould show "error 1" on the 5th attemt. This indicates that $skickat != '0', even though the databse indicates that emailSent == '0' for the second emails id. I think the error probably is that that the user id is not updated so it just checks for the first email id which == '1'. I´m still a beginner at PHP and Mysqli so that might not be the error so please take a look and let me know what you think. What do you think is the error and how could I fix this so I could use this for more accounts than one, preferably with the security of prepared statements?
Im not sure but I think you got a mistake here.
In the function getId you do a bind_param of the email as an integer where it should be a string.
It should be like this:
function getId($email, $mysqli)
{
if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE email = ? LIMIT 1"))
{
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->bind_result($resultat);
$stmt->fetch();
$stmt->close();
return $resultat;
}
else
{
// Could not create a prepared statement
header("Location: ../error.php?err=Database error: cannot prepare statement");
exit();
}
}