PHP MYSQL Prevent user or email inserted twice - php

I want to prevent if the user enters same email twice, which will create duplicate entry. Please help me to solve this small problem, I have searched stackoverflow for this problem but everyone has their own database with own method.
Thank you
<form action="create_subscriber.php" method="post">
<input placeholder="Name" name="inputName" type="name" required/>
<input name="inputEmail" placeholder="example#email.com" name="Submit" type="email" required/>
<input name="Submit" type="submit" value="Subscribe"/>
</form>
create_subscriber.php below
<?php
//include 'connection.php'
$dbhost = "localhost";
$dbuser = "sampleuser";
$dbpass = "samplepass";
$dbname = "sampledb";
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);
$name = $_POST['inputName'];
$email = $_POST['inputEmail'];
if(!$_POST['Submit']){
echo "Please enter a name & email";
//header('Location: index.php');
}else{
mysql_query("INSERT INTO subscriptions
(`ID`,`Name`, `Email`) VALUES(NULL,'$name', '$email' ) ")
or die(mysql_error());
echo "User has been added";
header('Location: success.php');
}
?>

Since you are not doing any validation, you can use the Email as a unique field and do an REPLACE query. http://dev.mysql.com/doc/refman/5.0/en/replace.html
I would strongly advise you to write validation in the form of a query check against the database prior to attempting to do a secondary insert. It's even made easy by persistent connections being available so you don't have the overhead of few ticks it takes to do that validation query.

mysql_query("INSERT INTO subscriptions
(`ID`,`Name`, `Email`) VALUES (NULL,'$name', '$email' )
WHERE NOT EXISTS (
SELECT email FROM subscriptions WHERE email='$email'
)")

Simply execute a preliminary query to check for email uniqueness
SELECT * FROM subscriptions WHERE `email` = ?
(I wrote the query in the form of a prepared statement
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
You should use prepared statement to inject values into queries).
If you get any row then the email is not unique so redirect to the original form page, possibly displaying an error message.
If you don't get any record then you may proceed with the insert and then render a "mail registration succeeded" page.
Btw: you can't echo something and then set a header. As you start sending output header can't be set/changed.

Related

Insert a value into database based on Session's User ID

Attempting to insert a Score based on the User's Session ID and POST , I've set up the database to use the UserID as a foreign key constraint but dont know how to do an insert query.
enter image description here
Database Values ^^
My attempt below
<?php
include("php/functions.php");
include('connections/conn.php');
$userID = $_SESSION["userID"];
//echo "all good here";
$newsoanxscore = mysqli_real_escape_string($conn, $_POST['socanxscore']);
$insertquery = "INSERT INTO socanxscore(socialanxietyscore)" . "VALUES('$newsoanxscore')";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
mysqli_close($conn);
?>
My insert form
<form action="insertsoanxietyscore.php" method="post">
Insert your score <input type="number" name="socanxscore" /><br><br>
<input type="submit" />
</form>
There are a few things here that may be helpful.
Firstly, you are not passing the user ID into your insert query. which can be written in this case as.
$insertquery = "INSERT INTO socanxscore(socialanxietyscore, UserId) VALUES('$newsoanxscore', '$userID')";
Secondly, please take the time to explore prepared queries to prevent SQL injection when passing end-user input to a database table. You may find the following resource useful.
http://php.net/manual/en/mysqli.prepare.php
go for this:
<?php
session_start();
include("php/functions.php");
include('connections/conn.php');
$userID = $_SESSION["userID"];
if(isset($_POST["socanxscore"]))
{
$query=INSERT INTO socanxscore(socialanxietyscore) VALUES('$newsoanxscore') WHERE userID=$userID";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
}
else
{
ehco "error";
}
mysqli_close($conn);
?>

Updating specific column in a particular row in mysql using php?

I have been trying to create a reset password feature for my website, where the user can insert the already registered email and that will generate a random OTP and will be stored in the same column as the user's details such as
id firstname lastname username email resetpassword
1 name last user email OTP
this is my code but it's not working.
<?php
require 'dbh.php';
session_start();
$random = mt_rand(1000,1000000);
$email = $_POST['email'];
$sql = "SELECT Email FROM registeredusers WHERE Email='$email'";
$result = mysqli_query($connection,$sql);
$emailCheck = mysqli_num_rows($result);
if (empty($email))
{
echo "please fill out all the fields";
}
else{
$result = mysqli_query($connection,$sql);
$sql = "UPDATE registeredusers SET ResetPassword='$random' WHERE Email='$email'";
Header("Location: submitOTP.php");
}
?>
I am just trying this out so the form looks something like this
<form action="resetPassword.php" method="POST">
<input type="text" value="email" name="email"></input>
<input type="submit" value="submit"></input>
</form>
You should firts assigne the sql code and after execute the query
$sql = "UPDATE registeredusers SET ResetPassword='$random' WHERE Email='$email'";
$result = mysqli_query($connection,$sql);
otherwise you simply repeat the previous (select ) query ..
and be careful for avoid sql injection take a look at prepared query and binding param

Secured Mysqli Statement to avoid SQL Injection but the form sends only blank Info

Good day! I'm having a problem in using $stmt to avoid SQL Injection on my database. Whenever I click submit, the form only sends blank user and password but there's an multiple id that has been created. :( Is there anyone who can help me through this?
Here's my Form
<form action="index.php" method="POST">
<h1>Create Username</h1>
Username: <input type="text" name="user"><br />
Password: <input type="password" name="pass"><br />
<input type="submit" value="Submit">
</form>
And my for Action is here.
$name = $_POST['user'];
$password = $_POST['pass'];
//$mysqli is my connection stored at my config.php
if ($stmt = $mysqli->prepare("INSERT INTO users (user, password) VALUES (?, ?)")) {
// Bind the variables to the parameter as strings.
$stmt->bind_param("ss", $name, $password);
// Execute the statement.
$stmt->execute();
// Close the prepared statement.
$stmt->close();
}
if($stmt){
echo "Data Sent";
}else{
echo "Error in Sending";
}
Mysqli doesn't quote like PDO. Do it manually.
INSERT INTO `users` (`user`, `password`) VALUES ('?', '?')
For validating user, if you are using password_hash() and password_verify() functions of php select them first and check password.
If you're using md5, sha1, ... first md5 the input password from post, then
select * from `users` where `username`= '...' AND `password` = 'Here it should be the hashed pw';

How to prevent username duplicates in mySQL (PHP) [duplicate]

This question already has answers here:
How to prevent duplicate usernames when people register?
(4 answers)
Closed 2 years ago.
This is how my users register for database, but my question is: How can I prevent the database from having copies of the same username, or in other words, how can I prompt to the user that "Your username already exists" if their username exists in the database.
<?php
$error = ""; // error
$GoodJob = "";
//When submit button is pressed, send data.
if(isset($_POST['submit'])){
if (empty($_POST['username']) || empty($_POST['email']) || empty($_POST['password'])) {
$error = "<br>Please insert only letters or numbers.";
}else{
// Define username, firstname, lastname, email and password.
$username = $_POST['username'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
// Define database information
$hostnameV = "***";
$usernameV = "***";
$passwordV = "***";
$databaseV = "***";
//connection to the database
$connection = mysql_connect($hostnameV, $usernameV, $passwordV)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db($databaseV,$connection)
or die("Could not select company");
// To protect MySQL injection for Security purposes
$username = stripslashes($username);
$firstname = stripslashes($firstname);
$lastname = stripslashes($lastname);
$email = stripslashes($email);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$firstname = mysql_real_escape_string($firstname);
$lastname = mysql_real_escape_string($lastname);
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
// SQL query to send information of registerd users
# FORMULA: INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)
$query = mysql_query("INSERT INTO `company`.`users` (`id`, `username`, `firstname`, `lastname`, `email`, `password`)
VALUES (NULL, '$username', '$firstname', '$lastname', '$email', '$password')", $connection);
//close the connection
mysql_close($connection);
} // end if statement
***
}
?>
<div id="main">
<div id="login">
<h2>REGISTER</h2>
<form action="" method="post">
<input id="name" name="username" placeholder="Pick a username" type="text">
<input id="name" name="email" placeholder="Your email" type="text">
<input id="name" name="firstname" placeholder="firstname" type="text">
<input id="name" name="lastname" placeholder="lastname" type="text">
<input id="password" name="password" placeholder="Create a password" type="password">
<input name="submit" type="submit" value=" REGISTER ">
<span><?php echo $error; ?></span>
</form>
</div>
</div>
I would first start by not using the mysql_* functions as they are deprecated and switch to PDO as it works correctly.
To answer your question, you should simply query the database for the username, if it exists, tell the user.
Before the Insert, using PDO and prepared statements.
$stmt = $dbh->prepare('SELECT count(*) FROM user WHERE username = ?');
$stmt->execute(array($username));
$res = $stmt->fetch(PDO::FETCH_NUM);
$exists = array_pop($res);
if ($exists > 0) {
// tell the user it already exists.
} else {
// carry on with your insert.
}
As others have suggested, making the username unique should also be done. I wouldn't write my code to fail though when trying to insert a duplicate username, I would still test if it exists.
So to provide a bit more clarity, in reference to the below comments about using exceptions, here's why I wouldn't write my code to throw an exception if someone enters a username that is already taken. Exceptions, in my opinion, should be exceptions. That means that something exceptional happened. Someone entering a username that is already taken, I consider that to be a normal operation of the application and it should be handled in a normal non-exceptional fashion. If however, someone entered a valid username and between the time that I checked that it was not taken and when I'm running my insert, someone else grabbed that username (in that 2 millisecond timeframe), that would be an exception and I would handle it. To the user, that "exception" would look exactly the same, but in my code it would be handled as an exception.
So that's why I wouldn't just write my code to do an insert that throws an exception when someone enters a username that is already taken. I would check whether it's taken or not and then insert it, throwing an exception if that username was snagged between the time I checked and when it was inserted. I think that's good application design and proper use of exceptions. Others can disagree, but that's how I would do it. Exceptions should be exceptional, not part of the normal course of doing business.
You can set a validation for checking the username is exist or not.
<?php
function checkUserExist($username){
$checkExist = "SELECT username from userTable WHERE username ='" . $username . "'" or die(mysql_error());
mysql_query($checkExist);
if($checkExist > 0){//That means username is existed from the table
return true;
}else{//username isn't exist
return false;
}
}
if(checkUserExist($username)){//function return true
echo "username is already exist, please change.";
}else{
//Insert the user info into db
}
This is an example for checking the username by using function with mysql_query, you can also use PDO to implement it, Cheers!

Using PHP to add to a database created in WAMP server?

Ok, so after installing wamp server, I have gone to the phpMyAdmin page and created a database called db2. After that, I have created a table inside of that database called cnt2. It has 5 columns, ID, Name, Mark1, Mark2 and Mark3. So, I have one html php file that allows you to view the information in the database, and this works just fine. However, my second html php document is supposed to allow you to add new information into the database. I have followed 2 different tutorials on this as I have never done php or any html script before, but it just isn't working. I'll post both codes/scripts below.
http://gyazo.com/467f8e3a066992c0753eec2d5912bdba << Database page
http://gyazo.com/82a1c2107fb75c4c2941583449b4504a << Input page with error
Database code
<html>
<body>
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db("db2",$dbhandle)
or die("Could not selected db2");
echo "Coneted to db2<br>", "<br>";
$result = mysql_query("SELECT ID, Name, Mark1, Mark2, Mark3 FROM cnt2");
while($row = mysql_fetch_array($result)){
echo "<b>Name: </b>".$row{'Name'}." <b>ID: </b>".$row{'ID'}." <b>First Mark: </b>".$row{'Mark1'}." <b>Second Mark: </b>".$row{'Mark2'}." <b>Third Mark: </b>".$row{'Mark3'}."<br>";
}
mysql_close($dbhandle);
?>
</body>
</html>
Input code
<HTML>
<?php
if($submit){
$db = mysql_connect("localhost", "root","");
mysql_select_db("db",$db);
$sql = "INSERT INTO cnt2 (ID, Name, Mark1, Mark2, Mark3) VALUES ('$id','$name','$markone','$marktwo','$markthree','$result = mysql_query($sql))";
echo "Thanks! Data received and entered.\n";
}
else{
?>
<form method="post" action="datain.php">
id:<input type="Int" name="ID"><br>
name:<input type="Text" name="Name"><br>
markone:<input type="Int" name="Mark1"><br>
marktwo:<input type="Int" name="Mark2"><br>
markthree:<input type="Int" name="Mark3"><br>
<input type="Submit" name="submit" value="Enter information">
</form>
<?
}
?>
</HTML>
Thanks for any help :)
You're not actually requesting your post headers to pull your vars in
<html>
<?php
if($submit){
//need to request post vars here
$id=mysql_real_escape_string($_POST['ID']);
$name=mysql_real_escape_string($_POST['Name']);
$markone=mysql_real_escape_string($_POST['Mark1']);
$marktwo=mysql_real_escape_string($_POST['Mark2']);
$markthree=mysql_real_escape_string($_POST['Mark3']);
$db = mysql_connect("localhost", "root","");
mysql_select_db("db",$db);
$sql = "INSERT INTO cnt2 (ID, Name, Mark1, Mark2, Mark3) VALUES ('$id','$name','$markone','$marktwo','$markthree')";
mysql_query($sql) or die(mysql_error()."<br />".$sql);
echo "Thanks! Data received and entered.\n";
}
else{
?>
<form method="post" action="datain.php">
id:<input type="Int" name="ID"><br>
name:<input type="Text" name="Name"><br>
markone:<input type="Int" name="Mark1"><br>
marktwo:<input type="Int" name="Mark2"><br>
markthree:<input type="Int" name="Mark3"><br>
<input type="Submit" name="submit" value="Enter information">
</form>
<?php // stop using short tags i've swapped it to a proper open
}
?>
</html>
Also if you're only just using don't use mysql_ functions look into mysqli or pdo especially prepared statements instead of directly injecting variables into queries as we have done above
The problem may be in this line:
$sql = "INSERT INTO cnt2 (ID, Name, Mark1, Mark2, Mark3) VALUES ('$id','$name','$markone','$marktwo','$markthree','$result = mysql_query($sql))";
As You may notice (at the end), it should probably be like this:
$sql = "INSERT INTO cnt2 (ID, Name, Mark1, Mark2, Mark3) VALUES ('$id','$name','$markone','$marktwo','$markthree')";
$result = mysql_query($sql);
As all other people mentioned, do not use mysql_* functions as they are DEPRECATED, instead of this stick with PDO or at least mysqli.
Also, the part
if($submit){
may never be satisfied unless You set the $submit variable somewhere before... Shouldn't it rather be
if (isset($_POST['submit'])) {
???
And, please, read about code formatting - Your code looks like crap... Best choice is to stick with PSR-0, PSR-1 and PSR-3 - use Google to read something about it...
create database android_api /** Creating Database **/
use android_api /** Selecting Database **/
create table users(
id int(11) primary key auto_increment,
unique_id varchar(23) not null unique,
name varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null
); /** Creating Users Table **/

Categories