Registration form: problems with email check - php

i have a problem with the realization of a registration form. My php script should check if the user email is already in use.
if the email is in use the php script should show an error message, if it is not the registration is successfully completed.
$email = $_POST['email'];
try{
$sql = "SELECT count(mail) FROM user WHERE mail = '$email'";
$result = $pdo->exec($sql);
}catch(PDOException $e){
echo $e;
exit(); }
if($result == 0){
//registration complete }
else{
//email already in use }
my problem is that i obtain always 0 as result also if the email is already inside the database. But if i execute that sql code inside my xampp' server i obtain 1 so the code works perfectly.
Thank you to all for help :)

You need to do this:
$email = $_POST['email'];
try{
$sql = "SELECT mail FROM user WHERE mail = :email";
$sql = $pdo->prepare($sql);
$sql->execute(array(':email'=> $email));
}catch(PDOException $e){
echo $e;
exit(); }
if($sql->rowCount() == 0){
//registration complete }
else{
//email already in use }

Related

How would I go by checking if email is already in use?

I have been working on my account creation page and I am stuck onto where I should be checking if email is already in use and how to go by it. would I need to make a query statement like this
Select * from Customers WHERE Email = $email)
and check that way?
<?php
session_start();
?>
<?php require_once("headerTH.html") ?>
<?php
$db= new PDO("sqlite:onlinestore.db");
if(ISSET($_POST['register'])){
$username = $_POST['username'];
$email = $_POST['email'];
$psw = sha1($_POST ['psw']);
$tel = $_POST['tel'];
if(! empty($email) && !empty($psw)) {
$query = "INSERT INTO Customers (UserName, Passwd, PhoneNumber, Email) VALUES(:UserName, :Passwd, :PhoneNumber, :Email)";
$result = $db->prepare($query);
$result->bindParam(":UserName", $username);
$result->bindParam(":Passwd", $psw);
$result->bindParam(":Email", $email);
$result->bindParam(":PhoneNumber", $tel);
// Account pass or fail
if($result->execute()){
echo"You have successfully created an account.{$_POST['email']}<br>";
}else{
///print_r($db->errorInfo());
require_once("create.php");
}
} else {
echo "all fields are required";
require_once("create.php");
}
} else {
require_once("create.php");
}
?>
<?php require_once("footerT.html")?>
I think the ideal way to do this is to check if the new email exists in the database, and based on that situation. The user will be able to create the account if the new email doesn't exist in the database, otherwise you should show an alert that email already exists.
Just required a simple if statment at the top
$stmt = $db->prepare("SELECT * FROM Customers WHERE Email=?");
$stmt->execute([$email]);
$user = $stmt->fetch();
if($user){
//email found
echo "Email already used";
}else if($result->execute()){
echo"You have successfully created an account.{$_POST['email']}<br>";
}else{
///print_r($db->errorInfo());
require_once("create.php");
}
} else {
echo "all fields are required";
require_once("create.php");
}
}
If it's me, YES, like what you said, I create a new function let say function checkUserByEmail($email) to check if the email already exists or not.
Then again you can use the same function if you need to check the user by email, let say at the time of login (if you using email for login).
By the way, DON't FORGET TO SANITIZE YOUR INPUTS ;)

Form values are not submitting into wamp server database with php (server -side ) validations

This file is the action file .When user submits wrong values , it heads back to the file named vform.php and asks user the correct input. But for me , after entering correct values and clicking on register , neither values are entering into wamp db, nor showing successful message. below is the code for adding values into db. after successful validation , it heads toregsuccess.php where it shows registration successful message. I don't know what exactly is the reason why values are not entering into db .
<?php
ob_start();
session_start();
include("DBConnection.php"); // include the connection object from the
DBConnection.php
if ($_POST['submit'])
{
$inFullname = trim($_POST["name"]);
$inEmail = trim($_POST["email"]);
$inPhone = trim($_POST["phonenumber"]);
$_SESSION['valid_name']=$inFullname;
$_SESSION['valid_email']=$inEmail;
$_SESSION['valid_phone']=$inPhone;
if( !preg_match("/^([a-zA-Z' ]+)$/",$inFullname) ||!preg_match('',$inEmail) || !preg_match('',$inPhone) ){
if(preg_match("/^[a-zA-Z-,]+(\s{0,1}[a-zA-Z-, ])*$/",$inFullname)){
$_SESSION['valid_name']=$inFullname;
}else {
$_SESSION['name_error'] = "enter valid name";
}
if(preg_match("/^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-
Za-z]{2,4})$/",$inEmail)){
$_SESSION['valid_email']=$inEmail;
} else{
$_SESSION['mail_error'] = "enter valid mail";
}
if(preg_match("/^\d{3}-\d{3}-\d{4}$/",$inPhone)){
$_SESSION['valid_phone']=$inPhone;
} else{
$_SESSION['phone_error'] = "enter valid phone number";
}
header('Location: vform.php');
die();
}
$stmt = $db->prepare("INSERT INTO DETAILS(NAME,EMAIL,PHONENUMBER) VALUES(?,?,?)"); //Fetching all the records with input credentials
$stmt->bind_param("sss", $inFullname,$inEmail,$inPhone); //Where s indicates string type. You can use i-integer, d-double
$stmt->execute();
$result = $stmt->affected_rows;
$stmt -> close();
$db -> close();
if($result > 0) {header("location: RegSuccess.php");} // user will be taken to the success page
else{ echo 'Oops. Something went wrong. Please try again Try Login';}
}
?>

php variable will not display in email

The assignment I'm working on (an E-commerce course) asks that I use php to generate a new password for a user and send the user an email with the new password. I successfully generate the password, send the email from my school's server to myself (a gmail account), using php mail() however the php variable representing the password is always blank. I have been looking for answers to this on here and other websites but cannot find what I'm doing wrong.
I am looking to solve this particular issue and am not looking to use PHPMailer or some other alternative. Also I am not looking to discuss more secure ways to send email, or discuss encryption, just looking to discuss this particular issue and why it is or isn't working. Thank you in advance for any advice.
if ($mysqli->conect_errno) {
die("Error: Could not connect to database." . $mysqli->connect_error);
} else {
echo "<p>Connected<br></p>";
}
$email = $_POST['email_input'];
try {
$password = reset_password($email, $mysqli);
notify_password($email, $password, $mysqli);
echo 'Your password has changed and has been emailed to you.<br>';
}
catch(Exception $e) {
echo 'Your password could not be reset';
}
function reset_password($email, $mysqli){
$new_password = randomString(8, 12);
if ($new_password == false) {
throw new Exception('could not generate new password');
}
$rand_number = rand(0, 999);
$new_password .= $rand_number;
echo "NEW PASSWORD: " .$new_password."\r\n";
$query = "UPDATE registration
SET password = sha1('".$new_password."')
WHERE email = '".$email."'";
$result = $mysqli->query($query);
if($result) {
echo "<br>Password Reset<br>";
}else {
echo "An error has occured";
}
}
function randomString($min_length, $max_length){
return substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), $min_length, $max_length);
}
function notify_password($email, $password, $mysqli){
$query = "SELECT email FROM registration WHERE email='".$email."'";
$result = $mysqli->query($query);
if(!$result){
throw new Exception('could not find email address');
}else if ($result->num_rows == 0) {
throw new Exception('Could not find email address:user not in database');
}else {
$row = $result->fetch_object();
$email = $row->email;
$from = "From support#HelpFinder \r\n";
$mesg = "Your password has been changed to ".$password."\r\n"."Please change it the next time you log in.\r\n";
if(mail($email, 'HelpFinder Login Information', $mesg, $from)) {
return true;
}else {
throw new Exception('Could not send email.');
}
}
}
the email message that arrives
example from text book I'm learning from
check if you are sending the $password variable as parameter correctly,
may be its empty
First please check that you have a double $result before the if declaration.
$result = $result = $mysqli->query($query);
After that you could try to make a var_dump to $password variable to check if it was correctly passed to the notify_password function. You could also post the $password variable definition so we could check in more depth.

PHP Email Confirmation Function MySQL Database error

There are many questions about email confirmation, databases, and permissions on Stackoverflow, but nothing I could find that would help me with this.
This specific question is directed to an email confirmation function built with PHP. The tutorial I am using can be found here: http://www.phpeasystep.com/phptu/24.html. Everything is working, however when the user clicks the email confirmation link (which would move their information from the temp_table to the confirmed_table), I receive this error:
Error updating database: No database selected
From what I have gathered from different sites/research/Stackoverflow questions is that this is due to the permissions of the database(s) I am working with (please correct me if it is another problem). I have read that I need to change all the users to be able to READ, but am unsure whether I should do this to both the databases as a whole (I couldn't find whether you can set the privileges for all the users in a database to automatically have the READ privileged), or the PHP when I add them to the temp_table. The tutorial I showed above doesn't say anything about it, so I am confused.
Registration form code:
<?php
session_start();
if(isset($_SESSION['aI']) || isset($_SESSION['pss'])) {
header("Location: pa.php");
}
include 'db.php';
if(isset($_POST['rSub'])) {
// connects to database using PHP Data Objects, throws exception if error in connection
try {
$conn = new PDO("mysql:host=$svrHost;db=$svrDb", $sUme, $sp);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "ERROR: " . $e->getMessage();
}
$error = '';
if($_POST['fN'] == '' || $_POST['lN'] == '' || $_POST['aI'] == '' || $_POST['eml'] == '' || $_POST['pss'] == ''
|| $_POST['pss2'] == '') {
$error = "<li style=\"color:#C70000; font-weight:bold;\"><center>- All fields are required. Try again.</font><center></li>";
}
if($error == '') {
$fN = ucfirst($_POST['fN']);
$lN = ucfirst($_POST['lN']);
$aI = $_POST['aI'];
$eml = $_POST['eml'];
$pss = $_POST['pss'];
$pss2 = $_POST['pss2'];
$admin = 0;
if($error != '') {
$error = "<ul>".$error."</ul>";
$_SESSION['error'] = $error;
}
else {
$hF = "$2y$10$"; // 2y = blowfish and 10 = num of hashes
$sa = "testsaltforwebsite1219"; //"random" 22-character sa
$fAS = $hF.$sa;
$sha = crypt($pss, $fAS);
// Random confirmation code
$c_cd=md5(uniqid(rand()));
$insert = $conn->prepare("INSERT INTO t_awhole (c_cd, fN, lN, aI, eml, pss)
VALUES (:c_cd, :fN, :lN, :aI, :eml, :pss)");
$insert->bindParam(':c_cd', $c_cd);
$insert->bindParam(':fN', $fN);
$insert->bindParam(':lN', $lN);
$insert->bindParam(':aI', $aI);
$insert->bindParam(':eml', $eml);
$insert->bindParam(':pss', $sha);
$result=$insert->execute();
// ---------------- Confirmation email ---------------- \\
// table name
$t_apart=t_awhole;
if($result){
// send e-mail to ...
$to=$eml;
// Your subject
$subject="Registration Confirmation";
// From
$header="from: no-reply#example.com"; //Need the address to send the eml to.
// Your message
$message="Copy and paste this link in your browser to activate your account: \r\n";
$message.="\n";
$message.="(serverAddress)/confirmation.php?passkey=$c_cd \r\n";
$message.="\n";
$message.="Thank you";
// send eml
$sml = mail($to,$subject,$message,$header);
}
// if not found
else {
echo "Your email Is Not Registered. Please Register.";
}
// if your email succesfully sent
if($sml){
echo '<script> window.location.href="emlC.php"</script>';
}
else {
echo "Cannot Send Confirmation Link To Your email Address.";
}
// ---------------- Confirmation email ---------------- \\
$_SESSION['aI'] = $aI;
$_SESSION['pss'] = $pss;
$_SESSION['admin'] = 0;
$stmt = $conn->prepare("SELECT DISTINCT dN, dU, ex FROM doc WHERE aI != '0'");
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $row)
{
$ex = $row['ex'];
$dU = $row['dU'];
$dN = $row['dN'];
$insert = $conn->prepare("INSERT INTO doc (dN, dU, aI, ex)
VALUES (:dN, :dU, :aI, :ex)");
$insert->bindParam(':aI', $aI);
$insert->bindParam(':ex', $ex);
$insert->bindParam(':dU', $dU);
$insert->bindParam(':dN', $dN);
$insert->execute();
}
}
}
?>
Confirmation page code:
<?php
include('db.php');
// passkey that got from link
$pk=$_GET['pk'];
$t_awhole_conf="t_awhole";
// Retrieve data from table where row that match this passkey
$sql_conf1="SELECT * FROM $t_awhole_conf WHERE confirm_code ='$pk'";
$result_conf=mysql_query($sql_conf1) or die ('Error updating database: '.mysql_error());
// If successfully queried
if($result_conf){
// Count how many row has this passkey
$count=mysql_num_rows($result_conf);
// if found this passkey in our database, retrieve data from table "t_awhole"
if($count==1){
$rows=mysql_fetch_array($result_conf);
$fN = $rows['fN']; // capitalizes the first letter (6-26-14)
$lN = $rows['lN']; // capitalizes the first letter (6-26-14)
$aI = $rows['aI'];
$eml = $rows['eml'];
$pss = $rows['pss'];
$pss2 = $rows['pss2'];
$a_whole_conf="a_whole";
// Insert data that retrieves from "t_awhole" into table "a_whole"
$sql_conf2="INSERT INTO $a_whole_conf(fN, lN, aI, eml, pss, admin)
VALUES ($fN, $lN, $aI, $eml, $pss, $admin)";
$result_conf2=mysql_query($sql_conf2);
}
// if not found passkey, display message "Wrong Confirmation code"
else {
echo "Wrong Confirmation code";
}
// if successfully moved data from table"t_awhole" to table "a_whole" displays message "Your account has been activated" and don't forget to delete confirmation code from table "t_awhole"
if($result_conf2){
echo "Your account has been activated";
// Delete information of this user from table "t_awholeb" that has this passkey
$sql_conf3="DELETE FROM $t_awhole_conf WHERE confirm_code = '$pk'";
$result_conf3=mysql_query($sql_conf3);
}
}
?>
In your Registration form code, you have two lines that create the connection to the database (new PDO ...). You can further use $conn to execute statements.
In your Confirmation code, you don't create any connection before calling mysql_query (why the switch from PDO to mysql functions ?).
See the mysql_query documentation here.

Undefined variable in PHP when referencing MySQL element

Edit: I solved the problem! It was an issue unrelated to the code that I posted - I had an exit command in the script - but all of your advice still helped in other ways.
I'm trying to automatically send an e-mail to a user when they fill out their picks on a sports website. The early part of the script works: Their picks are correctly inserted or updated in the database. The script breaks when I try to pull the user's e-mail address from a table in the MySQL database and use it to send them a message. But what is very strange about this bug is that it doesn't result in any error messages, and for some reason prevents certain echo statements from running while allowing others.
Here's the relevant code:
...
//set variable for the userID, grabbed from the session array
$userID = $_SESSION['identifier'];
...
//write query to get user's e-mail from the database
$getEmail = "SELECT `email` FROM `useraccounts` WHERE `userID` = '".$userID."'";
//execute query
$result = $db->query($getEmail);
//check if query failed
try
{
if (!$result)
{
throw new customexception("Some kind of database problem occurred when trying to find your e-mail address.");
}
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
//get the info from the row
$row = $result->fetch_assoc();
//check if function ran, catch exception if it failed
try
{
if ($row === false)
{
throw new customexception("Some kind of database problem occurred when trying to get your e-mail address from your user record in the database.");
}
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
//set e-mail variable
$email = $row['email'];
//set up e-mail information to send a record of their picks to the user
$toAddress = "$email";
$subject = "Your Picks";
$fromAddress = "From: picks#mysite.com";
//take the info the user submitted, format it for the e-mail, and assign to variable $mailContent
//the $winner1, $spread1, etc. variables are defined earlier in the function, and were successfully submitted into the database
$mailContent = "You picked $winner1 to win by $spread1 points, $winner2 to win by $spread2 points, $winner3 to win by $spread3 points, $winner4 to win by $spread4 points, and $winner5 to win by $spread5 points. \n".
"You can change your picks at any time before 1:00pm EST, February 27, 2011. Just go back to the form on the game page and enter your new picks. Good luck!";
//use wordwrap to limit lines of $mailContent to 70 characters
$mailContent = wordwrap($mailContent, 70);
//send the e-mail
$isMailed = mail($toAddress, $subject, $mailContent, $fromAddress);
//debug: check if mail failed
if (!$isMailed)
{
echo "Mail failed.";
}
//debug: echo $email to see if there's anything in there
echo "<p>E-mail: $email</p>";
//debug: echo $toAddress to see if there's anything in there
echo "<p>To address: $toAddress</p>";
//if everything succeeded, write reply and close database
echo $reply;
$db->close();
?>
Just to be clear, $userID is set correctly, because their picks enter the database like they're supposed to. None of the exceptions listed in the code come up, meaning the query seems to have run successfully. I checked the query again by copying it from the PHP code and running it directly on the MySQL database. When it ran directly, it found the correct e-mail address for every userID value I entered.
But the mail never gets delivered, and when I try to echo the $email and $toAddress variables to see if they're empty:
//debug: echo $email to see if there's anything in there
echo "<p>E-mail: $email</p>";
//debug: echo $toAddress to see if there's anything in there
echo "<p>To address: $toAddress</p>";
...nothing shows up. Not even an error message. And that doesn't necessarily mean that the variables are empty: Not even the labels are echoed.
I also tried the code with my personal e-mail hardcoded instead of $toAddress, and no mail was sent. So the mail function isn't working.
I should also note that the script still successfully echoes $reply (which is a string defined much earlier) at the end.
What's really strange is that the login script for my website uses an almost identical piece of code and works perfectly:
$getuserID = "SELECT `userID` FROM `useraccounts` WHERE `u_name` = '".$login."' AND `p_word` = SHA1('".$password."')";
$result = $db->query($getuserID);
//check if query ran, catch exception if it failed
try
{
if ($result === false)
{
throw new customexception("Some kind of database problem occurred when trying to find your user ID.");
}
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
//get the info from the row
$row = $result->fetch_assoc();
//check if function ran, catch exception if it failed
try
{
if ($row === false)
{
throw new customexception("Some kind of database problem occurred when trying to get info from your user record in the database.");
}
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
//set userID variable
$userID = $row['userID'];
//assign the session identifier and include successfullogin.html if all is well
$_SESSION['identifier'] = $userID;
And I used to have the signup script send me an e-mail every time I got a new user, so I know that mail() works in general with my hosting provider:
//set up static e-mail information
$toAddress = "myemail#mysite.com";
$subject = "Advance Sign-Up";
$mailContent = "Name: $firstName $lastName \n".
"Username: $username \n".
"Password: $password \n".
"E-mail: $email \n".
"Country: $country \n".
"State: $state \n".
"City: $city \n".
"ZIP: $zip \n";
$fromAddress = "From: $email";
...
mail($toAddress, $subject, $mailContent, $fromAddress);
This bug is completely mystifying to me. I wish I had some sort of error message to work with, at least. Can anyone see what's wrong?
It should be a comment but for the sake of formatting.
Your way of error handling is quite unusual.
If you really want to use exceptions, it should be done different way: one try block and multiple throws:
try
{
$getEmail = "SELECT `email` FROM `useraccounts` WHERE `userID` = '".$userID."'";
$result = $db->query($getEmail);
if (!$result)
{
throw new customexception("Some kind of database problem occurred when trying to find your e-mail address.");
}
$row = $result->fetch_assoc();
if ($row === false)
{
throw new customexception("Some kind of database problem occurred when trying to get your e-mail address from your user record in the database.");
}
$email = $row['email'];
$toAddress = "$email";
$subject = "Your Picks";
$fromAddress = "From: picks#mysite.com";
$mailContent = "yadda yadda yadda";
$mailContent = wordwrap($mailContent, 70);
mail($toAddress, $subject, $mailContent, $fromAddress);
}
catch (customexception $e)
{
include 'error.html';
echo $e;
$db->close();
include 'footer.php';
exit;
}
?>
Are you positive the database variables have contents? I use echo (or print) to quickly make sure the variables aren't empty. Are you positive your email code works? Try it with set values (such as your own personal e-mail) to make sure it works.
The best way out to ignore such notices is to ensure that the variables exist or in plain PHP, use isset(),if !isset() throw an exception/error and handle it properly.

Categories