PROBLEM: I am trying to UPDATE table data with a "forgot password key" where the email field matches the user's form input on a previous page.
I want to make sure the user's input is sanitized and a match can be found in the database.
ERROR: The code does not update the ForgotKey Field in my Database
Here is my code, error is happening on line 7 where stated in the comment.
$ForgotKeyLength = 9;
$ForgotKeyString = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$ForgotKey = substr(str_shuffle($ForgotKeyString), 0, $ForgotKeyLength); //shuffle String, start with 0, 9 characters long
$sql = "UPDATE UserTable SET ForgotKey = ".$ForgotKey." WHERE Email = ? ";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../forgot.php?error2"); // THE ERROR HAPPENS HERE, UNABLE TO PREP STATEMENT
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $Email);
mysqli_stmt_execute($stmt); // I believe this line should update the table
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
//success: send user their email from here
$variable = $row['Email'];
}
else {
header("Location: ../forgot.php?error5");
exit();
}
}
Related
I am building a log in system and every other part works perfectly fine except for the portion that cross references the entered password with the password in the database. So when I checked to see if the passwords match I realized that the password from the database is coming back as null. May I ask what is happening?? (There is no issue with the "uidExists" method, it seems to just be in the "loginUser" method).
This is based of of this video https://www.youtube.com/watch?v=gCo6JqGMi30
I believe its around the hour and 40 minute mark he gets to the loginUser function.
function loginUser($conn,$username,$pwd){
$uidExists = uidExists($conn,$username,$username);
if($uidExists === false){
header("location: ../login.php?error=wrongslogin");
exit();
}
else{
echo $pwd;
if(is_null($uidExists["userPwd"])){
echo "Empty bruv";
}
else{
echo $uidExists["userPwd"];
}
}
function uidExists($conn,$username,$email){
$sql = "SELECT * FROM users WHERE userUid = ? OR userEmail = ?;";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt,$sql)){
header("location: ../signup.php?error=stmtfailed");
exit();
}
mysqli_stmt_bind_param($stmt,"ss",$username,$email);
mysqli_stmt_execute($stmt);
$resultData = mysqli_stmt_get_result($stmt);
if(mysqli_fetch_assoc($resultData)){
return $row;
}
else{
$result = false;
return $result;
}
mysqli_stmt_close($stmt);
}
This doesn't look right:
$uidExists = uidExists($conn,$username,$username);
Should this be:
$uidExists = uidExists($conn,$username,$userPwd);
I have this function for email checking in registration form which disables submit button if submitted email is currently in use. So I want to modify that function in profile edit section. I also have profile edit form in profile.php. So when user edits his info withouth touching email input it works fine. But once user clicks and to email field and blurs out the mouse without even editing something it shows "Email Already Taken" error. Which is fine cause function works for registeration form. So when user submits different email I want to check if it's already in db otherwise if he doesn't change anything I want to show nothing and proceed.
I've tried to solve this in back end with this query:
SELECT * FROM users WHERE email = ? AND id != ?
.
.
.
mysqli_stmt_bind_param($stmt, "ss", $email, $uid);
but it doesn't work
Then I tried SELECT * FROM users WHERE email = ?
and looped over selection to detect if there is selection with id = uid. If yes, make result variable 0. But it also doesn't work.
function profEmailCheck(){
$('#email').blur(function(){
var email = $(this).val();
var uid = $('#uid').val();
var update_email_check = '';
$.ajax({
url:'update_email_check.php',
method:"POST",
data:{
update_email_check: update_email_check,
email: email,
uid: uid
},
success:function(data)
{
if(data != 0)
{
$('.email-availability').html('<span class="text-danger">Email Already Taken</span>');
$('#update-prof-btn').attr("disabled", true);
}
else
{
if (email == '')
{
$('.email-availability').html('');
$('#update-prof-btn').attr("disabled", true);
}
else
{
$('.email-availability').html('<span class="text-success">Email Available</span>');
$('#update-prof-btn').attr("disabled", false);
}
}
}
})
});
}
<?php
include('db_connect.php');
if (isset($_POST["update_email_check"])) {
$email = mysqli_real_escape_string($conn, $_POST["email"]);
$uid = mysqli_real_escape_string($conn, $_POST["uid"]);
$sql = "SELECT * FROM users WHERE email = ? AND id != ?";
$stmt = mysqli_stmt_init($conn);
$query = mysqli_query($conn, $sql);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "Something went wrong :(";
exit();
} else {
mysqli_stmt_bind_param($stmt, "ss", $email, $uid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
}
$result = mysqli_sql($conn, $sql);
while ($rows = mysqli_fetch_array($query, MYSQLI_ASSOC)){
if($rows['id'] == $uid){
$result = '0';
}
}
echo mysqli_num_rows($result);
}
As far as I understood you want to check email control.
If (exists){
Do something
}
else {
Do something
}
If this is what you want then you should;
$ControlMailQuery = "SELECT * FROM users WHERE email = ?";
$ControlMailQueryResult = mysqli_query($db, $ControlMailQuery);
if(mysqli_num_rows($ControlMailQueryResult) == 1){
//There is a one user who has this email
}
else{
//this is unique e-mail address
}
I am just wondering if we need to have the !isset function for email activation because we are not really filling out a form to check if the user has submitted the form or not but a link instead. I read somewhere that email activation can fail and one should also allow the user to activate their account manually but the following code should work but sometimes I do get the missing link error. However, all the variables are shown in my url though:
<?php
include_once __DIR__.'/header2.php';
if($_SESSION['u_uid']) {
echo "<meta http-equiv='refresh' content='0;url=../index.php?activatelevel2promo=mustloggedoutfirst'>";
exit();
} else {
if (!isset($_GET['email']) || !isset($_GET['activatetoken']) || !isset($_GET['duration'])) {
echo "<meta http-equiv='refresh' content='0;url=../index.php?activatelevel2promo=missinglink'>";
exit();
} else {
include_once __DIR__.'/dbh.php';
// retrieve the email and token from url
$activate = 0;
$email = strip_tags($_GET['email']);
$token = strip_tags($_GET['activatetoken']);
$duration = strip_tags($_GET['duration']);
$sql = "SELECT * FROM memberships WHERE user_email = ? AND token2 = ? AND activate2 = ?;";
$stmt = mysqli_stmt_init($conn);
//Prepare the prepared stement
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed";
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "ssi", $email, $token, $activate);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
$subscriptionplandate = date("Y-m-d H:i:s");
$level2promo_activate = 1;
if($duration == '1week') {
$expirydate = date('Y-m-d H:i:s', strtotime("+1 week"));
}
if($duration == '2weeks') {
$expirydate = date('Y-m-d H:i:s', strtotime("+2 week"));
}
if($duration == '3weeks') {
$expirydate = date('Y-m-d H:i:s', strtotime("+3 week"));
}
if($duration == '4weeks') {
$expirydate = date('Y-m-d H:i:s', strtotime("+1 month"));
}
$token = null;
$sql2 = "UPDATE memberships
SET subscriptionplandate2 = ?, expirydate2 = ?, token2 = ?, level2promo_activate = ?
WHERE user_email = ?;
";
$stmt = mysqli_stmt_init($conn);
//Prepare the prepared stement
if (!mysqli_stmt_prepare($stmt, $sql2)) {
echo "SQL statement failed";
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "sssis", $subscriptionplandate, $expirydate, $token, $level2promo_activate, $email);
mysqli_stmt_execute($stmt);
echo "<meta http-equiv='refresh' content='0;url=../index.php?activatelevel2promo=success'>";
exit();
}
}
}
}
}
This is what is been shown in the url:
https://www.pianocourse101.com/includes/activatelevel2promo.php?email=pianoforte0011#gmail.com&activatetoken=%5E#%rG%5EGTq#&duration=2weeks
because we are not really filling out a form to check if the user has submitted the form or not but a link instead
That doesn’t matter. Same as I could not fill out or remove a form field named foo, I could also remove a parameter ?bar=... from any URL before I call it - the result would be the same, a parameter your script is expecting, resp. needs to be able to properly perform its task, isn’t there. So yes, checking whether you got all the data you need, makes sense in both cases.
but the following code should work but sometimes I do get the missing link error. However, all the variables are shown in my url though
Yeah, well …
…?email=pianoforte0011#gmail.com&activatetoken=%5E#%rG%5EGTq#&duration=2weeks
What you have here, is one parameter with the name email and the value pianoforte0011#gmail.com, and one parameter named activatetoken with the value %5E, or ^ after URL decoding … and that’s it.
The rest of that URL is just the fragment identifier or “hash” - and that does not even get send to the server in the first place.
You neglected to properly URL-encode your parameter values here. The # is not supposed to have its special meaning here, so it needs to be encoded (%23)
You should either apply urlencode to all parameter values individually; or collect all your parameters and values in an array first, and then use http_build_query - that will do the complete job of creating the whole query string for you, and it takes care of the necessary encoding automatically while doing so.
http://php.net/manual/en/function.urlencode.php
http://php.net/manual/en/function.http-build-query.php
I'm trying to move the data from one column in my table, to another, and then setting the initial column back to zero. While the initial column is reset back to zero, it also adds that zero onto the end of target column (I'll provide some screenshots for context).
Here is my code:
function complete_da($da_id) {
include 'connect.php';
include 'globals.php';
retrieve_user_data($_SESSION['logged_in']);
nation_data_grab($_SESSION['logged_in']);
echo "u_n_i: ".$user_nation_information['active_da']." <br>";
$ret_da_info_sql = "SELECT `active_da`, `completed_da` FROM `nations` WHERE `nations`.`user_id` = ?;";
$ret_da_info_stmt = mysqli_stmt_init($connect);
if(!mysqli_stmt_prepare($ret_da_info_stmt, $ret_da_info_sql)) {
echo "Statement 1 Failed";
} else {
mysqli_stmt_bind_param($ret_da_info_stmt, "i", $user_data['id']);
mysqli_stmt_execute($ret_da_info_stmt);
// Use get_result for *, bind_result for specific columns
mysqli_stmt_bind_result($ret_da_info_stmt, $active_da, $completed_da);
mysqli_stmt_fetch($ret_da_info_stmt);
echo "u_n_i: ".$user_nation_information['active_da']." <br>";
$updated_cda_str = ($completed_da .= ",".$active_da);
}
mysqli_stmt_close($ret_da_info_stmt);
$update_compl_with_active_sql = "UPDATE `nations` SET `completed_da` = ? WHERE `nations`.`user_id` = ?;";
$update_compl_with_active_stmt = mysqli_stmt_init($connect);
if(!mysqli_stmt_prepare($update_compl_with_active_stmt, $update_compl_with_active_sql)) {
echo "Statement 2 Failed";
} else {
mysqli_stmt_bind_param($update_compl_with_active_stmt, "si", $updated_cda_str, $user_data['id']);
mysqli_stmt_execute($update_compl_with_active_stmt);
$set_active_zero_sql = "UPDATE `nations` SET `active_da` = ? WHERE `nations`.`user_id` = ?;";
$set_active_zero_stmt = mysqli_stmt_init($connect);
$zero = 0;
if(!mysqli_stmt_prepare($set_active_zero_stmt, $set_active_zero_sql)) {
echo "Statement 2 Failed";
} else {
mysqli_stmt_bind_param($set_active_zero_stmt, "ii", $zero, $user_data['id']);
mysqli_stmt_execute($set_active_zero_stmt);
}
mysqli_stmt_close($set_active_zero_stmt);
}
mysqli_stmt_close($update_compl_with_active_stmt);
mysqli_close($connect);
}
Here is my table before the function is run:
Before
Table after function has run:
After
When run, the debugging echos I used to check to see if the 'active_da' is set correctly produces this result (the 4 is the button ID, they are just triggers for the function for now):
Results from echo
My question is, how can I just simply transfer the 'active_da' column onto the end of the 'completed_da' column without adding that extra zero?
EDIT: I believe this is the query that's throwing it off
$set_active_zero_sql = "UPDATE `nations` SET `active_da` = ? WHERE `nations`.`user_id` = ?;";
$set_active_zero_stmt = mysqli_stmt_init($connect);
$zero = 0;
if(!mysqli_stmt_prepare($set_active_zero_stmt, $set_active_zero_sql)) {
echo "Statement 2 Failed";
} else {
mysqli_stmt_bind_param($set_active_zero_stmt, "ii", $zero, $user_data['id']);
mysqli_stmt_execute($set_active_zero_stmt);
}
When the user submits the form, the form information is posted to a php file and the php file redirects the user straight away to the next webpage once the form is submitted by using the header function. I have already validated the form using HTML and Javascript however the PHP has validation in it so that any errors that get past the Javascript and HTML are identified and the user is notified, however this is not possible at the minute as the user is redirected before they are notified.
How would I identify the user if the PHP locates an error?
Is it necessary as will the only errors be by people who are intentionally trying to be malicious?
My code is:
<?php
header("location: (next webpage)");
if(isset($_POST['submit'])){
$data_missing = array();
if(empty($_POST['email_banned'])){
// Adds name to array
$data_missing[] = 'Email';
} else {
// Trim white space from the name and store the name
$email_banned = trim($_POST['email_banned']);
}
if(empty($_POST['notes'])){
// Adds name to array
$data_missing[] = 'Notes';
} else {
// Trim white space from the name and store the name
$notes = trim($_POST['notes']);
}
if(empty($data_missing)){
require_once('mysqli_connect.php');
$query = "INSERT INTO banned_emails (id, email_banned, created_on, notes) VALUES ( NULL, ?, NOW(), ?)";
$stmt = mysqli_prepare($dbc, $query);
//i Interger
//d Doubles
//s Everything Else
mysqli_stmt_bind_param($stmt, "ss", $email_banned, $notes);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
if($affected_rows == 1){
echo 'Student Entered';
mysqli_stmt_close($stmt);
mysqli_close($dbc);
} else {
echo 'Error Occurred<br />';
echo mysqli_error();
mysqli_stmt_close($stmt);
mysqli_close($dbc);
}
} else {
echo 'You need to enter the following data<br />';
foreach($data_missing as $missing){
echo "$missing<br />";
}
}
}
?>
Thanks :)
You can use $_SESSION to store errors, and retrieve them later.
$_SESSION['errors'] = array('an error message', 'a second error message');
Then in the script the user has been redirected to :
while($err = array_shift($_SESSION['errors'])){
?>
<p class='p_error'><?=$err?></p>
<?php
}