PHP how to check for email already in MySQL database? - php

Hi I'm calling out for help from all the PHP Gods on Stackoverflow :)
I've created an email signup form (just 1 field for email), that is able to validate with Ajax and post a new email to the database from a basic PHP script I found.
However the next step I have to do is check if an email is already in the database before adding it. There are several questions exactly like this on Stack and I've tried all the answers however to no avail :( I'm not a PHP guy and haven't been able to hack it right yet.
Below is my current insert.php file which does work and does add a new email field into the database. However the code below that is the latest I've tried to use to check for an already existing email, but I get a send data error.
Working PHP file to add email
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydatabase", $con);
$sql="INSERT INTO newsletter (email)
VALUES
('$_POST[mail]')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "Thanks for subscribing!"; //Text on page
//header("Location: /thankyoupage.php"); //Redirect page
mysql_close($con)
?>
UPDATED CODE using PDO
Code below works to add emails, however still allows duplicates...
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = 'root';
/*** email ***/
$email = '$_POST[mail]';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mydatabase", $username, $password);
//$query = SELECT count(*) AS `total` FROM `data` WHERE `email` = '{$request}'
$query = SELECT COUNT(*) as 'count' FROM `data` WHERE email = '$_POST[mail]';
$row = mysql_fetch_assoc(mysql_query($query));
if($row['total']) {
echo 'Sorry email already exists';
}
else {
/*** echo a message saying we have connected & added email ***/
echo 'Thanks for subscribing!';
/*** INSERT data ***/
$count = $dbh->exec("INSERT INTO newsletter(email) VALUES ('$_POST[mail]')");
}
/*** echo a message saying we have connected & added email ***/
//echo 'Thanks for subscribing!';
/*** INSERT data ***/
//$count = $dbh->exec("INSERT INTO newsletter(email) VALUES ('$_POST[mail]')");
/*** echo the number of affected rows ***/
/*echo $count;*/
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Thanks in advance for anyone with the time to take a look at this :)
Extra Notes:
My database table is called newsletter and there are 2 fields (id - numbers only) & (email)

if email is an unique key, that would be simple
<?php
mysql_connect("localhost","root","root");
mysql_select_db("howdini");
$email = mysql_real_escape_string($_POST['mail']);
$sql="INSERT IGNORE INTO newsletter (email) VALUES ('$email')";
mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if (mysql_affected_rows()) {
header("Location: /thankyoupage.php"); //Redirect page
} else {
//already exists
}

Related

form input will not POST to MYSQL but will show on screen

The form sends the data to this page. The print_r outputs everything I want to put into the table onscreen to check it's there, but nothing goes to the table. I have only managed to populate the table manually in phpmyadmin. Iam sorry if it's a really easy fix - I have only been learning for two weeks!
There are no errors showing in the logs or on screen when I run the page. The print_r does echo the array as it should be but nothing appears in the table
<?php
session_start();
// Change this to your connection info.
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'users';
$username = ($_POST['username']);
$password = ($_POST['password']);
$companyName = ($_POST['companyName']);
$confirmPassword = ($_POST['confirmPassword']);
// Try and connect using the info above.
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS,
$DATABASE_NAME);
if (mysqli_connect_errno()) {
// If there is an error with the connection, stop the script and
display the error.
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
print_r ($_POST);
// Now we check if the data was submitted, isset() function will check
//if the data exists.
if (!isset($_POST['username'], $_POST['password'],
$_POST['companyName'])) {
// Could not get the data that should have been sent.
die ('Please complete the registration form!');
}
// Make sure the submitted registration values are not empty.
if (empty($_POST['username']) || empty($_POST['password']) ||
empty($_POST['companyName'])) {
// One or more values are empty.
die ('Please complete the registration form');
}
print_r ($_POST);
// We need to check if the account with that username exists.
if ($stmt = $con->prepare('SELECT id, password FROM phplogin WHERE
username = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), hash the
//password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the account exists in the
// database.
if ($stmt->num_rows > 0) {
// Username already exists
echo 'Username exists, please choose another!';
} else {
// Username doesnt exists, insert new account
/* $stmt = $con->prepare('INSERT INTO phplogin (username, password,
companyName ) VALUES (?, ?, ?)');*/
if (false !== true){
/* We do not want to expose passwords in our database, so hash the
password and use password_verify when a user logs in.
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$stmt->bind_param('sss', $_POST['$username'], $password,
$_POST['$companyName']);
$stmt->execute();*/
$sql = 'INSERT INTO phplogin (username, password, companyName )
VALUES ($username, $password, $companyName)';
echo 'You have successfully registered, you can now login!';
echo (" ".$password." ".$username." ".$companyName);
echo ' well done';
} else {
/* Something is wrong with the sql statement, check to make sure accounts table exists with all 3 fields.*/
echo 'Could not prepare the new statement!';
print_r ($_POST);
}
}
}
$con->close();
?>
//$sql = 'INSERT INTO phplogin (username, password, companyName ) VALUES ($_POST[username], $password, $_POST[companyName])';
PHP thinks it should execute VALUES even though it is not any proper action. Use /* THIS IS COMMENT */ because it prevents stuff like this happening.
Also as a side note: Do not assign values in if statement. You can assign $stmt on its own line and just check
If($stmt === true) {}
Or
If($stmt !== true) {}
You get the point.
Also another side note is that you should prefer using PDO. It is alot of easier to handle and understand because of ts syntax and it makes OOP much much more easier. Mysqli is ok to use, but i personally do not recommend using it.

PHP MySQL. Add table contents does not work

If I want to add content to the table using "INSERT INTO", I don't get an error message and the table is not filled. I'm new with PHP. explanations would be nice. The database runs on XAMPP.
I don't know what to try. I've already used another table, but it doesn't work. The user should have full access to the table. The names also match.
<?php
$username = $_POST["username"];
$passwort = $_POST["passwort"];
$mail = $_POST["mail"];
$passwort2 = $_POST["passwort2"];
$pass = sha1($passwort);
$db = mysqli_connect("localhost", "phptest1", "o84XM5wxo65QBjkF", "phptest1");
if($passwort == $passwort2) {
echo "Password is correct.";
$db = "INSERT INTO user (Username, Mail, Password) VALUES ('$username', '$mail', '$pass')";
} else if(!($passwort == $passwot2)) {
echo "Password is not correct";
} ?>
The variable $db actually contains information about the connection. You cannot insert a query into your database the way you are trying to
You can use $db (in your case) in order to check whether the connection has been correctly established or not and then if everything works correctly you can user mysqli_query() to inject the query into your database.
You can do it like so:
<?php
if(isset($_POST['submit'])){ //You have to check if your submit button is pressed
$username = $_POST["username"];
$passwort = $_POST["passwort"];
$mail = $_POST["mail"];
$passwort2 = $_POST["passwort2"];
$pass = sha1($passwort);
$db = mysqli_connect("localhost", "phptest1", "o84XM5wxo65QBjkF", "phptest1");
if(!$db){
die('Connection could not be established! Check provided information');
}
if($passwort == $passwort2) {
echo "Password is correct.Inserting query now";
$query = "INSERT INTO user (Username, Mail, Password) VALUES ('$username', '$mail', '$pass')";
$result = mysqli_query($db, $query); //keep $result for debugging purposes.
} else {
die("Password is not correct");
} //no need for else if as there are only 2 conditions.
if(!$result){ //check if query was successful.
die('Query Error');
}
echo "Query Updated successfully";
}
?>
This code is really simplistic and for testing purposes only.
I just wanted to show you the way you can send queries to your database. You better use other encryption techniques i.e. crypt() and of course functions like mysqli_real_escape_string() when retrieving data from users, in order to avoid potential injection attacks.
Check this post for more info about preventing injections.
Hope that helps.

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.

Copying data from a MySQL table to another MySQL table not showing

I'm trying to make a registration form that validates the account by sending a validation code to the email. Once the user receive the code in his email he must click the link to validate his account(I simulated this using the localhost). BTW, I have 2 database for the registered members and for the temporary members(these are the members that are waiting for validation).
When the validation code is processed and matched, the data from the temporary table will be copied to the registered members table, after the copying is done the user data from temporary table will deleted.
when I checked my updated database(registered members table) the ID column had incremented but the username, password and email field has no data. what is the problem here?
here is the website I'm following for the tutorial but I did some little tweaks
http://phpeasystep.com/phptu/24.html
localhost/validated_email.php?passkey=639900974e5fc25626af1a6ce5da8b01
<html>
<body>
<?php
ob_start();
//define a function for temporary database (temporary_members)
function temporary_members_db(){
$host="localhost";
$db_username="root";
$db_password="";
$db="forum_members";
$db_table="temporary_members";
//=======================connect to database
mysql_connect("$host","$db_username","$db_password") or die("Could not connect to the database!");
mysql_select_db("$db") or die("database not found!");
}
function members_db() {
$host="localhost";
$db_username="root";
$db_password="";
$db="forum_members";
$db_table="members";
//=======================connect to database
mysql_connect("$host","$db_username","$db_password") or die("Could not connect to the database!");
mysql_select_db("$db") or die("database not found!");
}
//connect to the temporary_member table
temporary_members_db();
$code = $_GET['passkey'];
//execute mysql query to check the validation code
$check_code = "SELECT `validation_code` FROM `temporary_members`";
$execute_code = mysql_query($check_code);
$result_code = mysql_num_rows($execute_code);
if ($result_code==1) {
$rows=mysql_fetch_array($execute_code);
$username = $rows['username'];
$password = $rows['password'];
$email = $rows['email'];
$table_members = "members";
members_db();
$copy_values = "INSERT INTO $table_members(username, password, email) VALUES ('$username', '$password', '$email')";
$execute_copy = mysql_query($copy_values);
}
else {
echo "Wrong validation code";
}
if ($execute_copy) {
echo "Your account has been activated!";
//delete data from the temporary_members
$table_temporary_members = "temporary_members";
$delete_data = "DELETE FROM $table_temporary_members WHERE validation_code = '$code'";
$execute_delete = mysql_query($delete_data);
}
ob_end_flush();
?>
</body>
</html>

PHP display data from MySQL using GET

I'm trying to look up user's username using $_GET but not actually seing the result of the query. Here's the code:
<?php
$host = "localhost";
$username = "root";
$password = "toor"; // :)
$database = "db";
$link = mysql_connect($host, $username, $password);
if(!$link){
exit('Could not connect to database: '. mysql_error());
}
$email = mysql_real_escape_string(htmlspecialchars(stripslashes($_GET["e"])));
$query = "SELECT username FROM cc_card WHERE email = '$email'";
$result = mysql_query($query);
if(mysql_num_rows($result)){
$user = mysql_fetch_assoc($result);
echo $user['username'];
} else {
echo "Something's wrong";
}
it's only returnung "Something's wrong". I wanted it to display the username field of the cc_card table where email = email. What am I doing wrong?
If you're getting "Something's wrong" from the posted code it means nowhere in the cc_card table does the email column match the email value you specify in your query.
You need to verify that the contents of your sanitized $email variable do, in fact, exist somewhere in the table. Try:
} else {
echo "Something's wrong";
var_dump($email);
}
To see the contents of the sanitized $email variable and manually query the database from the shell (or phpmyadmin or whatever) to find whether the value you're specifying exists or not. I'm betting it doesn't exist.
You'd better add the error check after the query.
if (!$result) {
die('Error: ' . mysql_error());
}
If no error, then it means there is no matched email in your database.

Categories