How to avoid duplicate emails php / sql? - php

I used this code and I don't know what is the problem and I used different codes as well
what I want to do to check and not allow the user to add his email twice
<?php
include("includedb.php");
//declare variables
$name = $_POST['name'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$gift = $_POST['gift'];
$formName = $_POST['formName'];
$formEmail = $_POST['formEmail'];
$formEmirate = $_POST['formEmirate'];
$birthday = $_POST['birthday'];
$date = $_POST['date'];
$result = mysqli_query("SELECT * FROM users WHERE email = '$email'") or exit(mysqli_error()); //check for duplicates
$num_rows = mysqli_num_rows($result); //number of rows where duplicates exist
if ($num_rows == 0) { //if there are no duplicates...insert
$sql = "INSERT INTO users (name, email, tel, gift, formName, formEmail, formEmirate, birthday, date)
VALUES ('$name', '$email', '$tel','$gift', '$formName', '$formEmail', '$formEmirate','$birthday',CURRENT_TIMESTAMP )";
if (!mysqli_query($sql)) {
die('Error: ' . mysqli_error());
}
}
mysqli_close();
header("location: thank-you.html?remarks=success");
?>

the problem is you are not passing any connection to the mysql_query
thus the queries are not getting queried
$conn = your connection;
$result = mysqli_query($conn,"SELECT * FROM users WHERE email = '$email'") or exit(mysqli_error()); //check for duplicates
$num_rows = mysqli_num_rows($result); //number of rows where duplicates exist
if($num_rows == 0) { //if there are no duplicates...insert
$sql = "INSERT INTO users (name, email, tel, gift, formName, formEmail, formEmirate, birthday, date)
VALUES ('$name', '$email', '$tel','$gift', '$formName', '$formEmail', '$formEmirate','$birthday',CURRENT_TIMESTAMP )";
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error());
}
}

thanks for support I found what has worked with me please find the code below and please advise me how to make it secure and protect it from sql injection
if(isset($_POST['submit'])){
$name= $_POST['name'];
$email= $_POST['email'];
$result = mysqli_query($conn,"SELECT * FROM test WHERE email = '$email'") or exit(mysqli_error()); //check for duplicates
$num_rows = mysqli_num_rows($result); //number of rows where duplicates exist
if(($num_rows) > 0){
echo "A record already exists.";
exit;
}
else{
$sql = "INSERT INTO test (name, email)
VALUES ('$name', '$email')";
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error());
}
}
if($result) {
header("Location: game.html");
}else{ echo "Not Successful"; }
mysqli_close();
}
?>
<!DOCTYPE html>
<head>
</head>
<body>
<h2>Enter your Name and Email</h2>
<form method="post">
<p><strong>First Name:</strong><br /> <input type="text" name="name" /></p>
<p><strong>email:</strong><br /> <input type="email" name="email"/></p>
<input type="submit" name="submit" value="Add Customer" />
</form>
</body>
</html>

Related

MySQL database could not be updated with PHP program

addmember.php
<?php
require_once("dbtools.inc.php");
$account = $_POST["account"];
$password = $_POST["password"];
$name = $_POST["name"];
$sex = $_POST["sex"];
$year = $_POST["year"];
$month = $_POST["month"];
$day = $_POST["day"];
$telephone = $_POST["telephone"];
$address = $_POST["address"];
$email = $_POST["email"];
$comment = $_POST["comment"];
$link = create_connection();
$sql = "SELECT * FROM users Where account = '$account'";
$result = execute_sql($link, "member", $sql);
if (mysqli_num_rows($result) != 0)
{
mysqli_free_result($result);
echo "<script type='text/javascript'>";
echo "alert('Account already in use! Please choose another username');";
echo "history.back();";
echo "</script>";
}
else
{
mysqli_free_result($result);
$sql = "INSERT INTO users (account, password, name, sex,
year, month, day, telephone, address,
email, comment) VALUES ('$account', '$password',
'$name', '$sex', $year, $month, $day, '$telephone',
'$address', '$email', '$comment')";
$result = execute_sql($link, "member", $sql);
echo "User added successfully!";
}
mysqli_close($link);
?>
join.html
<form action="addmember.php" method="POST" name="myForm">
(Different types of input)
<input type="submit" value="Add">
My aim is to add a member data into the database after the user clicked the Add button on the form in join.html. However the page could run echo "User added successfully!"; this line but the problem is the database could not get updated even though I already called execute_sql command. May I ask what is missing in order to be connected with the database?

check if the email is already in database when creating a new acount

So i want to check if the email is already in database when creating a new account but i do not know how to make it work , because i am a beginner in php
<?php
if (isset($_POST["register"]))
{
include 'header.php';
$firstName = $connection->real_escape_string($_POST["firstName"]);
$email = $connection->real_escape_string($_POST["email"]);
$password = sha1($connection->real_escape_string($_POST["password"]));
$sql = "SELECT * FROM users WHERE email LIKE '%$email%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if($queryResult >0)
echo"Email already exists";
else
{
$connection = new mysqli('mysql.hostinger.com', 'xxx', 'xxx', 'xxx');
$data = $connection->query("INSERT INTO users (username, email, password) VALUES ('$firstName', '$email', '$password')");
if ($data === false)
echo "Eroare!";
else
header( 'Location:http://alergii-help.tk/account/login.php');
}}
?>
<input type="submit" class="login100-form-btn" name="register" value="Inregistrare" required />
i don't know what is not working
the table is caled "article"
Why don't you add a unique constraint for email in the table using below query?
ALTER TABLE USERS ADD CONSTRAINT UNQ_EML UNIQUE (EMAIL)
If your code tries to insert an already existing email, then MySQL will throw such duplicate data exception while inserting and you can easily catch it and identify. Below is pseudo code to check.
if( mysql_errno() == 1062) {
// Duplicate key
} else {
// Non duplicate
}
https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
Try:
<?php
if (isset($_POST["register"])) {
include 'header.php';
$connection = new mysqli('xxxx', 'xxx', 'xxx', 'xxxx');
$firstName = $connection->real_escape_string($_POST["firstName"]);
$email = strtolower($connection->real_escape_string($_POST["email"]));
$password = sha1($connection->real_escape_string($_POST["password"]));
$sql = "SELECT * FROM users WHERE LOWER(email) = '$email';";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if($queryResult >0)
echo"Email already exists";
} else {
$data = $connection->query("INSERT INTO users (username, email, password) VALUES ('$firstName', '$email', '$password')");
if ($data === false) {
echo "Eroare!";
} else {
header( 'Location:http://alergii-help.tk/account/login.php');
}
}
}
?>
You need the first make the connection and then pass it before statement:
$result = mysqli_query($conn, $sql)
like below:
$conn = new mysqli('mysql.hostinger.com', 'u784726611_teze', 'b567c63b567c63', 'u784726611_teze');
$result = mysqli_query($conn, $sql);

Data is retrieved from DB but wont insert?

So when I want to retrieve data and check it i.e. if the email already exist echo already registered. That part works fine, however inserting the same data does not work. Are my conditionals ordered improperly?
(intentionally left out values for the dbhostname id pw variables)
$dbname = "hw2";
$link = mysqli_connect($dbhostname, $dbuserid, $dbpassword, $dbname);
$firstname = $_POST["signup-firstname"];
$lastname = $_POST["signup-lastname"];
$email = $_POST["signup-email"];
$password = $_POST["signup-password"];
$repassword = $_POST["signup-repassword"];
if ($password != $repassword){
echo "<br><h3>Passwords did not match. <br>Please try again.</h3>";
}
else {
$ret_email = "SELECT * FROM hw2 WHERE email = '$email'";
$result = mysqli_query($link, $ret_email);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0){
echo "This email is already registered.";
}
else{
$insert_query = "INSERT INTO hw2 (firstname, lastname, email, password, repassword) VALUES ('$firstname', '$lastname', '$email', '$password', '$repassword')";
echo "$insert_query";
}
}
?>
You should perform the query not only echoing it
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
if ($num_rows > 0){
echo "This email is already registered.";
}
else{
$insert_query = "INSERT INTO hw2 (firstname, lastname, email, password, repassword) VALUES ('$firstname', '$lastname', '$email', '$password', '$repassword')";
echo "$insert_query";
mysqli_query($link,$insert_query)
}

Insert form data into MySQL database

Hi Guys I am having a problem that when adding form data into a database. For some reason the data is not inserted. here is my code:
<?php include_once 'secure/connect.php'; ?>
<?php
$name = "Your Name";
$email = "Your Best Email";
$msg_to_user = "";
if ($_POST['name'] != ""){
//Be sure to filter this data to deter SQL injection
$name = $_POST['name'];
$name = stripslashes($name);
$name = strip_tags($name);
$email = $_POST['email'];
$email = stripslashes($email);
$email = strip_tags($email);
$sql = mysql_query("SELECT * FROM newsletter WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if(!$email){
$msg_to_user = '<h4><font color="FF0000">Please Type an email address ' . $name . '</font></h4>';
} else if ($numRows > 0) {
$msg_to_user = '<h4><font color="FF0000">' . $email . ' is already in our system</font></h4>';
} else {
$sql_insert = mysql_query("INSERT INTO newsletter (name, email, dateTime) VALUES ('$name', '$email', now())") or die (mysql_error());
$msg_to_user = '<h4><font color="0066FF">Thanks' . $name . ', You have been added successfully</font></h4>';
$name = "";
$email = "";
}
}
?>
And my html form looks like this:
<div class="topForm">
<H3 style="text-align:center">SIGN UP FOR OUR NEWSLETTER</H3>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="name" value="<?php echo $name; ?>"/>
<input type="text" name="email" value="<?php echo $email; ?>"/><br/>
<input name="mySubmitBtn" type="submit" value="SUBMIT">
<?php echo $msg_to_user; ?>
</form>
</div>
Many thanks in advance all
Phillip
This is what I have now and nothing is still working...
<?php
$name = "Your Name";
$email = "Your Best Email";
$msg_to_user = "";
if ($_POST['name'] != ""){
include_once 'secure/connect.php';
//Be sure to filter this data to deter SQL injection
$name = $_POST['name'];
$name = stripslashes($name);
$name = strip_tags($name);
$email = $_POST['email'];
$email = stripslashes($email);
$email = strip_tags($email);
$sql = mysql_query("SELECT * FROM newsletter WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if(!$email){
$msg_to_user = '<h4><font color="FF0000">Please Type an email address ' . $name . '</font></h4>';
} else if ($numRows > 0) {
$msg_to_user = '<h4><font color="FF0000">' . $email . ' is already in our system</font></h4>';
} else {
$sql_insert = mysql_query("INSERT INTO newsletter (name, email) VALUES ('".$name."', '".$email."')") or die (mysql_error());
$msg_to_user = '<h4><font color="0066FF">Thanks' . $name . ', You have been added successfully</font></h4>';
$name = "";
$email = "";
}
}
?>
without regard to other errors or inconsistencies. also let me note that you should use mysqli or pdo. but php uses time()
$sql_insert = mysql_query("
INSERT INTO newsletter
(name, email, dateTime)
VALUES
('$name', '$email', ".time().")
");
or if you want a date time instead of the timestamp you can use the date() function.
You have to change now() from your code. And Use Following code.
$time = time() ;
$sql_insert = mysql_query("INSERT INTO newsletter (name, email, dateTime) VALUES ('".$name."', '".$email."', '".$time."' )") or die (mysql_error());
make sure you are connected to the database ! see what echo mysql_error(); says
if a form was submitted, catch the values, and then sanitize
insert query
ps: see what the following do:
if(isset($_POST['name']) ...
echo mysql_insert_id();
time() not now()
see the id of the new data inserted
your code, should work, if you follow these steps, and if you are connected to the database

Unknow php error in sql INSERT INTO

I have problem in my registration.
Look on my code:
//player.php
<?php
session_start();
class Player
{
var $name;
function _construct($name)
{
$this->$name = $name;
}
function CreatePlayer($name, $pass, $mail, $date, $type)
{
if($_POST['submit'])
{
$link = mysql_connect("localhost","wewewe", "wewewe");
if(!$con)
{
die( $return = mysql_error());
}
mysql_select_db("wewewe", $con);
mysql_query("INSERT INTO USERS (name, pass, mail, date, type) VALUES ('$name', '$pass', '$mail', '$date','$type')");
mysql_close(link);
}
return $return;
}
function LoginPlayer($name, $pass)
{
$link = mysql_connect("localhost","username", "pass");
mysql_select_db("con", $con);
$result = mysql_query("SELECT FROM USERS WHERE pass='$pass' AND name='$name'");
$count = mysql_num_rows($result);
if($count==1)
{
$_SESSION['name'] = $name;
$_SESSION['logged'] = true;
}
mysql_close($link);
}
}
?>
//reg.php
<html>
<form action="log.php" method="post">
Meno: <input type="text" name="meno">
<br>
Heslo: <input type="text" name="heslo">
<br>
Mail: <input type="text" name="mail">
<br>
Date: <input type="text" name="date">
<br>
Type: <input type="text" name="type">
<br>
<input type="submit">
<br>
</form>
<?php
include 'player.php';
$name = $_POST['meno'];
$pass = $_POST['heslo'];
$mail = $_POST['mail'];
$date = $_POST['date'];
$type = $_POST['type'];
$obj = new Player($name);
$res = $obj->CreatePlayer($name, $pass, $mail, $date, $type);
if($res==true)
{
echo "jo!";
}
else
{
echo $res;
}
?>
My problem is that if I write text to all fields and press ok, my page will restart but without any error message. And when I will look to a database, theres nothing. Why? Can anybody plese help me?
EDIT:
<?php
session_start();
class Player
{
var $name;
function _construct($name)
{
$this->$name = $name;
}
function CreatePlayer($name, $pass, $mail, $date, $type)
{
if($_POST['submit'])
{
$con = mysql_connect("localhost","wewewe", "wewewe");
if(!$con)
{
die( $return = mysql_error());
}
mysql_select_db("wewewe", $con);
$query = "INSERT INTO USERS (name, pass, mail, date, type) VALUES ('$name', '$pass', '$mail', '$date','$type')";
$retrn = var_dump($query); // SHOWS YOU QUERY STRING
mysql_query($query) or die(mysql_error()); // EXECUTES QUERY OR THROWS EXCEPTON (SHOWS ERROR TOO)
mysql_close($con);
}
return $return;
}
function LoginPlayer($name, $pass)
{
$link = mysql_connect("localhost","username", "pass");
mysql_select_db("con", $con);
$result = mysql_query("SELECT FROM USERS WHERE pass='$pass' AND name='$name'");
$count = mysql_num_rows($result);
if($count==1)
{
$_SESSION['name'] = $name;
$_SESSION['logged'] = true;
}
mysql_close($link);
}
}
?>
I think its not going inside if($_POST['submit'])
change
<input type="submit">
to
<input name="submit" type="submit" />
<input type="submit"> modify to <input type="submit" name="submit">
To debug SQL INSERTING :
mysql_select_db("wewewe", $con);
mysql_query("INSERT INTO USERS (name, pass, mail, date, type) VALUES ('$name', '$pass', '$mail', '$date','$type')");
mysql_close(link);
modify to
mysql_select_db("wewewe", $con);
$query = "INSERT INTO USERS (name, pass, mail, date, type) VALUES ('$name', '$pass', '$mail', '$date','$type')";
var_dump($query); // SHOWS YOU QUERY STRING
mysql_query($query) or die(mysql_error()); // EXECUTES QUERY OR THROWS EXCEPTON (SHOWS ERROR TOO)
mysql_close(link);
Your query in the function LoginPlayer is incorrect. You may simply fix it like this
$result = mysql_query("SELECT name FROM USERS WHERE pass='$pass' AND name='$name'");

Categories