The script is already working fine but I want to insert a command that allows only if the username is not yet used.
if (isset($_POST['submit'])) {
$firstname = htmlentities($_POST['firstname'], ENT_QUOTES);
$lastname = htmlentities($_POST['lastname'], ENT_QUOTES);
$position = htmlentities($_POST['position'], ENT_QUOTES);
$username = htmlentities($_POST['username'], ENT_QUOTES);
$password = htmlentities($_POST['password_two'], ENT_QUOTES);
$uniqid = uniqid('', true);
if ( $firstname == '' || $lastname == '' || $position == '' || $username == '' || $password == '') {
$error = 'ERROR: Please fill in all required fields!';
renderForm($error, $firstname, $lastname, $position, $username, $password);
} else {
if ($stmt = $connection->prepare("INSERT INTO employee (uniqid, firstname, lastname, position, username, password) VALUES (?, ?, ?, ?, ?, ?)")) {
$stmt->bind_param("ssssss", $uniqid, $firstname, $lastname, $position, $username, $password);
$stmt->execute();
$stmt->close();
} else {
echo "ERROR: Could not prepare SQL statement.";
}
header("Location: regemployee.php");
}
} else {
renderForm();
}
Make username unique on the DB, then when you try to insert the same username in to the DB again, the insert will through an error.
Alternatively you could do a SELECT * FROM employee WHERE username = ? and check if results is > 0.
Then you would know it exists already.
Do another SELECT query which checks if the submitted username already exist:
$stmt = $connection->prepare("SELECT * FROM employee WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
Then get the number of results:
$stmt->store_result();
$noofres = $stmt->num_rows;
$stmt->close();
Then, create a condition that if it yet doesn't exist, it will do the insert query:
if($noofres == 0){
/* INSERT QUERY HERE */
} else {
echo 'Username already taken.';
}
Related
I have this PHP code, which registers a user. All form validation is done by jQuery and the request is sent by Ajax to this PHP page. Everything is working fine except it’s not checking if email and mobile is already registered.
<?php
require('db_connection.php');
$error = "";
if($_SERVER['REQUEST_METHOD'] == "POST"){
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$password = $_POST['password'];
$hashed_password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$stmt = $conn->prepare("SELECT `user_email`, `user_mobile` FROM `users` where `user_email` = ? && `user_mobile` = ? LIMIT 1");
$stmt->bind_param("si", $email, $mobile);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows() > 0){
$row = $stmt->fetch();
if($email == isset ($row['user_email'])){
echo "email exists";
}
if($mobile == isset($row['user_mobile'])){
echo "mobile exists";
}
}else{
$stmt = $conn->prepare("INSERT INTO `users`(`user_name`, `user_email`, `user_mobile`, `user_password`) values (?, ?, ?, ?)");
$stmt->bind_param("ssis", $name, $email, $mobile, $hashed_password);
$stmt->execute();
echo "successfull";
}
$stmt->close();
}
$conn->close();
?>
from my observation the problem is somewhere I'm fetching the rows, because the registration is happening with different email and mobile.
I want to insert in the security the same id from users:
<?php
if (isset($_POST['reg_user'])) {
require 'db.php';
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password_1'];
$passwordRepeat = $_POST['password_2'];
$firstName = $_POST['firstname'];
$lastName = $_POST['lastname'];
$country = $_POST['country'];
$city = $_POST['city'];
$address = $_POST['address'];
$zipCode = $_POST['zipCode'];
if (empty($username) || empty($email) || empty($password) || empty($passwordRepeat) || empty($firstName) || empty($lastName) || empty($country) || empty($city) || empty($address) || empty($zipCode)) {
header("Location: ../sign_up.php?error=emptyfields&uid=" . $username . "&mail=" . $email);
exit();
} elseif (strlen($username) < 3) {
header("Location: ../sign_up.php?error=short_username=" . $username . "");
exit();
} elseif (strlen($username) > 17) {
header("Location: ../sign_up.php?error=long_username=" . $username . "");
exit();
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $username)) {
header("Location: ../sign_up.php?error=invalidmailuid");
exit();
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../sign_up.php?error=invalidmail&uid=" . $username);
exit();
} elseif (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
header("Location: ../sign_up.php?error=invaliduid&mail=" . $email);
exit();
} elseif ($password !== $passwordRepeat) {
header("Location: ../sign_up.php?error=passwordcheck&uid=" . $username . "&mail=" . $email);
exit();
} else {
$sql = "SELECT username FROM users WHERE username=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../sign_up.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
header("Location: ../sign_up.php?error=usertaken&mail=" . $email);
exit();
} else {
$sql = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../sign_up.php?error=sqlerror");
exit();
} else {
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sss", $username, $email, $hashedPwd);
mysqli_stmt_execute($stmt);
$sql = "INSERT INTO security (username, firstName, lastName, country, city, address, zipcode) VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "sssssss", $username, $firstName, $lastName, $country, $city, $address, $zipCode);
mysqli_stmt_execute($stmt);
header("Location: ../sign_up.php?signup=succes");
exit();
}
}
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
} else {
header("Location: ../sign_up.php");
exit();
}
Replace username from security with id from "users" table, but I don't know the id from this user because it executes at the same time, any solutions?
P.S: ID, auto increment primary key
I want to know that security data is from that user (id).
You can get the last inserted id in mysqli using
$conn->insert_id;
Right after executing the insertion of the item. ($conn being the instance of the msqli class)
Everthing seems to work except inserting data stmt.
I've added closing the connection and adding closing the statement.
$error = $user = $pass = "";
if (isset($_SESSION['user'])) destroySession();
if (isset($_POST['user']))
{
$user = sanitizeString($_POST['user']);
$pass = sanitizeString($_POST['pass']);
if ($user == "" || $pass == "")
$error = 'Not all fields were entered<br><br>';
else
{
$stmt = $connection->prepare('SELECT * FROM members WHERE user=?');
$stmt->bind_param('s', $user);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows)
$error = 'That username already exists<br><br>';
else
{
$hashedPwd = password_hash($pass, PASSWORD_DEFAULT);
$stmt = $connection->prepare("INSERT INTO members (user, pass) VALUES (?,?)");
$stmt->bind_param("ss", $user, $hashedPwd);
$stmt->execute;
$stmt->close();
die('<h4>Account created</h4>Please Log in.</div></body></html>');
}
}
}
$connection->close();
I can expect the code to recognize if a user exists. However, I can not expect the database to be updated with a new user.
Placing error_reporting(E_ALL); at the top of the page will show that there is problem with the $stmt->execute;
$stmt->execute; should be stmt->execute();
I am new to Prepared Statements in Php and and wondering how you would best approach checking if a row already exists as I seem to be getting confused at this stage:
<?php
include '../config.php';
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $email, $password);
if(mysqli_num_rows($stmt) > 0) {
$email = $_POST['email'];
$password = $_POST['password'];
$stmt->execute();
header('Location: ../login.php');
} else {
echo 'user already exists';
}
$stmt->close();
$conn->close();
?>
The above returns the else statement, if I switch them around it will insert again making use of the else statement and inserting the record but still not checking.
** UPDATE **
Here is my updated code for you to see after assistance below..
<?php
include '../config.php';
ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
$email = $_POST['email'];
$password = $_POST['password'];
$stmt_check = $conn->prepare("SELECT * FROM users WHERE email =?");
$stmt_check->bind_param("s", $email);
$stmt_check->execute();
if($stmt_check->num_rows > 0) {
echo 'user already exists';
} else {
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $email, $password);
$stmt->execute();
// header('Location: ../login.php');
}
$stmt->close();
$conn->close();
?>
mysqli_num_rows applicable to SELECT statement.
$stmt_check = $conn->prepare("SELECT * FROM users WHERE email =? AND password =?");
$stmt_check->bind_param("ss", $email, $password);
$stmt_check->execute();
if(mysqli_num_rows($stmt_check) > 0)
Updated Code
<?php
include '../config.php';
$email = $_POST['email'];
$password = $_POST['password'];
$stmt_check = $conn->prepare("SELECT * FROM users WHERE email =? AND password =?");
$stmt_check->bind_param("ss", $email, $password);
$stmt_check->execute();
if($stmt_check->num_rows > 0){
echo 'user already exists';
} else {
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $email, $password);
$stmt->execute();
header('Location: ../login.php');
}
$stmt->close();
$conn->close();
?>
Quick Link
mysqli_num_rows
mysql_num_rows
Which States,
This command is only valid for statements like SELECT or SHOW that
return an actual result set. To retrieve the number of rows affected
by a INSERT, UPDATE, REPLACE or DELETE query, use
mysql_affected_rows().
Edit 1
Change
if(mysqli_num_rows($stmt_check) > 0){
To
if($stmt_check->num_rows > 0){
See Example2 of PHP mysqli_num_rows() Function
This is my updated code, please try
<?php
include '../config.php';
$email = $_POST['email'];
$password = $_POST['password'];
$stmt_check = $conn->prepare("SELECT * FROM users WHERE email =? AND password =?");
$stmt_check->bind_param("ss", $email, $password);
$stmt_check->execute();
$stmt_check->store_result();
$numberofrows = $stmt_check->num_rows;
if(($numberofrows) > 0)
echo 'user already exists';
} else {
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $email, $password);
$stmt->execute();
header('Location: ../login.php');
}
$stmt->close();
$conn->close();
?>
Take a look at mysqli_stmt_affected_rows()
<?php include '../config.php';
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $_POST['email'], $_POST['password']);
$stmt->execute();
if(mysqli_stmt_affected_rows($stmt) > 0)
{
header('Location: ../login.php');
}
else
{
echo 'user already exists';
}
$stmt->close();
$conn->close();
?>
<?php include '../config.php';
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $_POST['email'], $_POST['password']);
$result = $stmt->execute(); // this return a bool: true if row affected otherwise false
if($result)
{
header('Location: ../login.php');
}
else
{
echo 'user already exists';
}
$stmt->close();
$conn->close();
?>
I'm a beginner here and i am learning the basic in converting from MySQL to MySQLi. I am currently working on this registration page which I would want to convert to the new MySQLi. Please advise me how to modify this script, I would prefer the procedural style.
UPDATE - The MySQLi coding is not working because it would insert into the database like the MySQL coding would, would appreciate if your can help me.
MYSQL
<?php
error_reporting(1);
$submit = $_POST['submit'];
//form data
$name = mysql_real_escape_string($_POST['name']);
$name2 = mysql_real_escape_string($_POST['name2']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$password2 = mysql_real_escape_string($_POST['password2']);
$email2 = mysql_real_escape_string($_POST['email2']);
$address = mysql_real_escape_string($_POST['address']);
$address2 = mysql_real_escape_string($_POST['address2']);
$address3 = mysql_real_escape_string($_POST['address3']);
$address4 = mysql_real_escape_string($_POST['address4']);
$error = array();
if ($submit) {
//open database
$connect = mysql_connect("localhost", "root", "Passw0rd") or die("Connection Error");
//select database
mysql_select_db("logindb") or die("Selection Error");
//namecheck
$namecheck = mysql_query("SELECT * FROM users WHERE email='{$email}'");
$count = mysql_num_rows($namecheck);
if($count==0) {
}
else
{
if($count==1) {
$error[] = "<p><b>User ID taken. Try another?</b></p>";
}
}
//check for existance
if($name&&$name2&&$email&&$password&&$password2&&$email2&&$address&&$address2&&$address3&&$address4) {
if(strlen($password)<8) {
$error[] = "<p><b>Password must be least 8 characters</b></p>";
}
if(!preg_match("#[A-Z]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 upper case characters</b></p>";
}
if(!preg_match("#[0-9]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 number</b></p>";
}
if(!preg_match("#[\W]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 symbol</b></p>";
}
//encrypt password
$password = sha1($password);
$password2 = sha1($password2);
if($_POST['password'] != $_POST['password2']) {
$error[] = "<p><b>Password does not match</b></p>";
}
//rescue email match check
if($_POST['email2'] == $_POST['email']) {
$error[] = "<p><b>Rescue Email must not be the same as User ID</b></p>";
}
//generate random code
$random = rand(11111111,99999999);
//check for error messages
if(isset($error)&&!empty($error)) {
implode($error);
}
else
{
//Registering to database
$queryreg = mysql_query("INSERT INTO users VALUES ('','$name','$name2','$email','$password','$password2','$email2','$address','$address2','$address3','$address4','$random','0')");
$lastid = mysql_insert_id();
echo "<meta http-equiv='refresh' content='0; url=Activate.php?id=$lastid&code=$random'>";
die ();
}
}
}
?>
MYSQLI (NOT WORKING)
<?php
error_reporting(1);
$submit = $_POST['submit'];
//form data
$name = mysqli_real_escape_string($connect, $_POST['name']);
$name2 = mysqli_real_escape_string($connect, $_POST['name2']);
$email = mysqli_real_escape_string($connect, $_POST['email']);
$password = mysqli_real_escape_string($connect, $_POST['password']);
$password2 = mysqli_real_escape_string($connect, $_POST['password2']);
$email2 = mysqli_real_escape_string($connect, $_POST['email2']);
$address = mysqli_real_escape_string($connect, $_POST['address']);
$address2 = mysqli_real_escape_string($connect, $_POST['address2']);
$address3 = mysqli_real_escape_string($connect, $_POST['address3']);
$address4 = mysqli_real_escape_string($connect, $_POST['address4']);
$error = array();
if ($submit) {
//open database
$connect = mysqli_connect("localhost", "root", "Passw0rd", "logindb") or die("Connection Error");
//namecheck
$namecheck = mysqli_query($connect, "SELECT * FROM users WHERE email='{$email}'");
$count = mysqli_num_rows($namecheck);
if($count==0) {
}
else
{
if($count==1) {
$error[] = "<p><b>User ID taken. Try another?</b></p>";
}
}
//check for existance
if($name&&$name2&&$email&&$password&&$password2&&$email2&&$address&&$address2&&$address3&&$address4) {
if(strlen($password)<8) {
$error[] = "<p><b>Password must be least 8 characters</b></p>";
}
if(!preg_match("#[A-Z]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 upper case characters</b></p>";
}
if(!preg_match("#[0-9]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 number</b></p>";
}
if(!preg_match("#[\W]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 symbol</b></p>";
}
//encrypt password
$password = sha1($password);
$password2 = sha1($password2);
if($_POST['password'] != $_POST['password2']) {
$error[] = "<p><b>Password does not match</b></p>";
}
//rescue email match check
if($_POST['email2'] == $_POST['email']) {
$error[] = "<p><b>Rescue Email must not be the same as User ID</b></p>";
}
//generate random code
$random = rand(11111111,99999999);
//check for error messages
if(isset($error)&&!empty($error)) {
implode($error);
}
else
{
//Registering to database
$queryreg = mysqli_query($connect, "INSERT INTO users VALUES ('','$name','$name2','$email','$password','$password2','$email2','$address','$address2','$address3','$address4','$random','0')");
$lastid = mysqli_insert_id();
echo "<meta http-equiv='refresh' content='0; url=Activate.php?id=$lastid&code=$random'>";
die ();
}
}
}
?>
Converting to mysqli is not about adding i to the old library.
The main difference is that mysqli offers prepared statement feature.
This saves you from the tedious task of manually escaping values with mysqli_real_escape_string.
The proper way to do it is to prepare your query:
$query = "INSERT INTO users VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ($stmt = mysqli_prepare($connect, $query)) {
mysqli_stmt_bind_param($stmt,'sssssssssssss', $name,$name2,$email,$password,$password2,$email2,$address,$address2,$address3,$address4,$random,'0');
/* execute prepared statement */
mysqli_stmt_execute($stmt);
/*Count the rows*/
if( mysqli_stmt_num_rows($stmt) > 0){
echo"New Record has id = ".mysqli_stmt_insert_id($stmt);
}else{
printf("Errormessage: %s\n", mysqli_error($connect));
die();
}
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
In addition to prepared statement, another advantage is the coding style, mysqli introduces OOP style, here is the same code in that style:
$query = "INSERT INTO users VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ($stmt = $connect->prepare($query)) {
$stmt->bind_param('sssssssssssss', $name,$name2,$email,$password,$password2,$email2,$address,$address2,$address3,$address4,$random,'0');
/* execute query */
$stmt->execute();
/*Count the rows*/
if($stmt->num_rows > 0){
echo"New Record has id = ".$connect->insert_id;
}else{
var_dump($connect->error);
die();
}
/* close statement */
$stmt->close();
}
/* close connection */
$connect->close();
Both would achive the same. Good luck
I noticed one error in your script (mysqli script):
Instead of
$count = mysql_num_rows($namecheck);
do
$count = mysqli_num_rows($namecheck);
You can also check for errors in your query, like this (from w3schools - http://www.w3schools.com/php/func_mysqli_error.asp):
if (!mysqli_query($con,"INSERT INTO Persons (FirstName) VALUES ('Glenn')"))
{
echo("Error description: " . mysqli_error($con));
}
Also try to do some debugging (echo some results) in your script to find errors.
Pass connection parameter inside
$lastid = mysqli_insert_id();
like
$lastid = mysqli_insert_id($connect);