am currently working on a project and i have the script for insertion.my table is called survey and the fields are id,username,password,province. the username is set to unique key. the insertion process is working fine without any duplicate entry but when i try to insert a duplicate entry at always shows me this error
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'bluff' for key 'username'
I know what this error mean, my problem is that how can i can if username already exist or not i want an alert message to pop up..
here is my code
class.user.php
public function username($username){
$stmt = $this->db->prepare("SELECT count(*) FROM tish_images WHERE username = :username");
$stmt->execute(array($username));
$number_of_rows = $result->fetchColumn();
if($number_of_rows >= 1) {
echo 'username does exist'; // or return so you get the value
} else {
echo 'username does not exist'; //also return?
}
}
public function create($username,$password,$province)
{
try
{
$stmt = $this->db->prepare("INSERT INTO tish_images(username,password,province) VALUES(:username, :password, :province)");
$stmt->bindparam(":username",$username);
$stmt->bindparam(":password",$password);
$stmt->bindparam(":province",$province);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
index.php
<?php
include_once 'DB.php';
$username = isset($_GET['username']) ? $_GET['username'] : '';
$password = isset($_GET['password']) ? $_GET['password'] : '';
$province = isset($_GET['province']) ? $_GET['province'] : '';
if(isset($_FILES['files'])){
$id = $_GET['id'];
$username = $_POST['username'];
$password = $_POST['password'];
$province = $_POST['province'];
if($crud->upload($id,$FILE_NAME,$FILE_SIZE,$FILE_TYPE,$username,$password,$province))
{
echo "<script type='text/javascript'>alert('Successfully Updated!');</script>";
}
else
{
echo "<script type='text/javascript'>alert('Updating Failed!');</script>";
}
}
if(isset($_GET['id']))
{
$id = $_GET['id'];
extract($crud->getID($id));
}
You should run a SELECT before performing the query to see if the username exists.
// count how many rows with user name exists
$checkUserStmt = $this->db->prepare("
SELECT count(1)
FROM tish_images
WHERE username = :username
");
$checkUserStmt->execute(array(":username" => $username));
// fetch the count result
if ($checkUserStmt->fetchColumn() > 0) {
// username already exists
} else {
// username available
} //if
A few notes.
You still might get a duplicate entry error if you have two users trying to register the same username at close interval.
You should hash the password see Secure hash and salt for PHP passwords
To check if username or email already exists. I added email in there as this is also useful. You don't want two users with the same email address. Well I wouldn't see the need for it. :)
Complete code added and up to date.
$query_check_user_name = $this->db_connection->prepare('SELECT user_name, user_email FROM users WHERE user_name=:user_name OR user_email=:user_email');
$query_check_user_name->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$query_check_user_name->bindValue(':user_email', $user_email, PDO::PARAM_STR);
$query_check_user_name->execute();
$result = $query_check_user_name->fetchAll();
if ($result > 0) {
echo "Someone with that username/email already exists.";
} else {
//Continue with proccessing the form
}
OR
$query_check_user_name = $this->db_connection->prepare('SELECT user_name, user_email FROM users WHERE user_name=:user_name OR user_email=:user_email');
$query_check_user_name->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$query_check_user_name->bindValue(':user_email', $user_email, PDO::PARAM_STR);
$query_check_user_name->execute();
$result = $query_check_user_name->fetchAll();
if ($result > 0) {
return true;
} else {
return false;
}
Related
The script doesn't throw any error, but if all the input fields are entered correctly, it just refreshs, and nothing happens.
I have included $salt and $link in header.php.
I might have overdid loops, but I spent couple of hrs trying to figure it out before posting it here.
<?php
if (array_key_exists('username', $_POST)||array_key_exists('pass', $_POST)||array_key_exists('email', $_POST)) {
if ($_POST["username"]!== "" && $_POST["email"]!== "" && $_POST["pass"]!== "" && $_POST['cpass']!== "" ){
if($_POST['pass']==$_POST['cpass']){
if (!mysqli_connect_error()) {
$query = "SELECT `username`, `email` FROM `users` WHERE `username` = '".mysqli_real_escape_string($link, $_POST['username'])."' OR `email` = '".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
if ($row = mysqli_fetch_array($result)) {
if ($row['username'] == $_POST['username']) {
echo "Username already exists!<br>";
//die("Awe! Someone took this username");
}
if ($row['email'] == $_POST['email']) {
echo "Email has been used once!<br>";
//die(":( Email is in use!");
}else if($row['username'] !== $_POST['username'] && $row['email'] !== $_POST['email']){
$email = mysqli_real_escape_string($link, $_POST["email"]);
$username = mysqli_real_escape_string($link, $_POST["username"]);
$pass = md5($salt.mysqli_real_escape_string($link, $_POST["pass"]));
$query = "INSERT INTO `users`( `username`, `pass`, `email`) VALUES ('$username', '$pass', '$email')";
if(mysqli_query($link, $query)){
echo "You were successfully registered";
} else {
echo "Something went wrong, Couldn't register at the moment!";
}
}
}
}else{
echo "An Error Occured while connecting !";
}
}else {
echo "Password didn't match!";
}
}else{
echo "Field(s) can't be left blank!";
}
}
?>
The problem of your code happens on :
if ($row = mysqli_fetch_array($result)) {
and since you didn't place any else for this "if" you don't see anything happens.
The problem is, this condition becomes true only if email or username is already inside the table.
so if given username and/or email is not already in the table, this condition becomes false and therefore it never reaches to inside block where you want to insert the new data.
There is also a side issue with this and lets say your query fetch 2 rows.. imagine this table.
userid - username - email
1 - user1 - user1#test.com
2 - user2 - user2#test.com
now lets say the given input data are
$_POST['username'] = 'user1';
$_POST['email'] = 'user2#test.com';
this will fetch 2 rows in your users table, but as you didn't make a loop you will only check for first row and it might cause bug or unexpected behavior in your script.
UPDATE : I also made a piece of code based on your code.. hope it helps you...
function validateInputs(){
$keys = array('username','pass','cpass','email');
foreach($keys as $key){
if(!isset($_POST[$key]) || empty($_POST[$key])){
throw new Exception("Field(s) can't be left blank!");
}
}
}
function validatePassword(){
if($_POST['pass'] !== $_POST['cpass']){
throw new Exception("Password didn't match!");
}
}
function checkForUniqueInput($email,$username){
global $link;
$query = "SELECT username, email FROM users WHERE username = '".$username."' OR email = '".$email."'";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
throw new Exception("Username and/or email already exist");
}
}
function insertNewUser($email,$username,$pass){
global $link;
$query = "INSERT INTO users( username, pass, email) VALUES ('".$username."', '".$pass."', '".$email."')";
if(!mysqli_query($link, $query)){
throw new Exception("Something went wrong, Couldn't register at the moment!");
}
}
if(isset($_POST)){
try{
validateInputs();
validatePassword();
$email = mysqli_real_escape_string($link, $_POST["email"]);
$username = mysqli_real_escape_string($link, $_POST["username"]);
$pass = md5($salt.mysqli_real_escape_string($link, $_POST["pass"]));
checkForUniqueInput($email,$username);
insertNewUser($email,$username,$pass);
echo 'You were successfully registered';
}
catch(Exception $e){
echo 'Error : '.$e->getMessage();
}
}
I have read all other PDO topic in stackoverflow and tried all the stuff, but still its not working, i don't know whats wrong
on the Edit/Change Password page
I am using this code
ob_start();
session_start();
require_once './../account/config.php';
$id = $_SESSION['id'];
if (isset($_POST["submit"])) {
$opwd = mysql_real_escape_string($_POST['oldpwd']);
$npass = mysql_real_escape_string($_POST['newpwd']);
$anpass = mysql_real_escape_string($_POST['renewpwd']);
$sql = "SELECT COUNT(*) AS count from users where id = :id";
try {
$stmt = $DB->prepare($sql);
$stmt->bindValue(":id", $id);
$stmt->execute();
$result = $stmt->fetchAll();
here, $result[0]["password"] is not fetching the result from table users and column password
I even tried $result["password"] but not working,
in other pages same method is working very perfect but here its not fetching result
So, even user puts correct old password, its returning Current Password is Incorrect
if($result[0]["password"] !== $opwd) {
$msg = "Current Password is Incorrect";
}
elseif($npwd !== $rnpwd) {
$msg = "New Passwords did not match.";
}
elseif (($result[0]["password"] === $opwd) && $npwd === $rnpwd) {
$sql = "UPDATE `users` SET (`password`, `retype`) = (:npswd , :anpwd) WHERE `id` = :id";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":npswd", $npass);
$stmt->bindValue(":anpwd", $anpass);
$stmt->bindValue(":id", $id);
$stmt->execute();
$msg = "Your Password is changed successfully";
$msgType = "success";
}
else {
$msg = "Error Occured. Please Contact us if you have some issue.";
}
}
catch (Exception $ex) {
echo $ex->getMessage();
}
}
Please guide me what am i missing here
I'm using PDO in my login (as instructed previously over sqli), and I have tried the following, but yet I am getting this Fatal Error, and cannot figure out what to give it, so it satisfies the error:
if($query->rowCount() > 0)
{
// session stuff
// refresh page
}
Then I tried this:
if($query->rowCount() == 1)
{
// session stuff
// refresh page
}
Yet I still get this: Fatal error: Call to a member function rowCount() on a non-object
Here's is what I started with before the changes:
$count = $query->rowCount();
Lastly, here's a better snippet so you can get an idea of what's involved:
<?php
include("/scripts/Connections.php");
$email = $_POST['email'];
$username = $_POST['username'];
$password = md5($_POST['password'], "DDerehOjhdfDDf$$##%^)-=_/.#$#dkfsj!`~efjkf(*)/)sD");
$confPassword = md5($_POST['conPassword'], "DDerehOjhdfDDf$$##%^)-=_/.#$#dkfsj!`~efjkf(*)/)sD");
if(isset($email, $username, $password, $confPassword)) {
if(strstr($email, "#")) {
if($password == $confPassword) {
$query = $dbc->prepare("SELECT * FROM members WHERE username = ? OR email = ?");
$query = $query->execute(array(
$username,
$email
));
$count = $query->rowCount();
if($count == 0) {
$query = $dbc->prepare("INSERT INTO memebers SET username = ?, email = ?, password = ?");
$query = $query->execute(array(
$username,
$email,
$password
));
if($query) {
echo "Your account has been registered, you may login!";
}
}
else {
echo "A user already exists with that username/password.";
}
}
else {
echo "Your passwords do not match!";
}
}
else {
echo "Invalid email address!";
}
}
?>
Can anyone point where I'm going wrong here. This is my only error this is being thrown.
You appear to be overwriting $query with the boolean return value from execute(), leaving you with a non-object value (boolean) which you're trying to call a method on.
Try something like this:
if($password == $confPassword) {
$query = $dbc->prepare("SELECT * FROM members WHERE username = ? OR email = ?");
$result = $query->execute(array(
$username,
$email
));
// check the value of $result is true here - if not,
// your query has failed to execute and handle the error
// appropriately.
$count = $query->rowCount();
// ...
}
$query = $dbc->prepare("SELECT * FROM members WHERE username = ? OR email = ?");
$query->execute(array($username, $email)):;
$count = $query->rowCount();
echo "Value is " . $count;
Try this.
I have this login and registration script from the net. Everything is working fine.
Objectives:
Usernames entered by the user will only be alphabets. If the username entered is not exist in the database, it will automatically add a number 1 on the username, example, user1.
Let's say the database have already had user1, user2, user3. Whenever a user entered user, it will then check what is the last incrementing number which in this case, it is 3, so it will then add into the database as user4.
Problems:
As I am trying to learn PDO as much as I could and it is still pretty difficult for me to understand. Also, I do not have any idea where should I start from.
Below are my current working code:
if (isset($_POST['submit'])) {
if(empty($_POST['username']) || empty($_POST['password'])){
$errors[] = 'All fields are required.';
}else if(!ctype_alpha($_POST['username'])){
$errors[] = 'Please enter only alphabet letters.';
}else{
if ($users->user_exists($_POST['username']) === true) {
$errors[] = 'That username already exists';
}
}
if(empty($errors) === true){
$username = htmlentities($_POST['username']);
$password = $_POST['password'];
$users->register($username, $password);
header('Location: register.php?success');
exit();
}
}
public function user_exists($username) {
$stmt = $this->db->prepare("SELECT COUNT(`id`) FROM `userinfo` WHERE `username`= ?");
$stmt->bindValue(1, $username, PDO::PARAM_STR);
try{
$stmt->execute();
$rows = $stmt->fetchColumn();
if($rows == 1){
return true;
}else{
return false;
}
} catch (PDOException $e){
die($e->getMessage());
}
}
public function register($username, $password){
$password = sha1($password);
$stmt = $this->db->prepare("INSERT INTO `userinfo` (`username`, `password`) VALUES (?, ?) ");
$stmt->bindValue(1, $username, PDO::PARAM_STR);
$stmt->bindValue(2, $password, PDO::PARAM_STR);
try{
$stmt->execute();
// mail($email, 'Please activate your account', "Hello " . $username. ",\r\nThank you for registering with us. Please visit the link below so we can activate your account:\r\n\r\nhttp://www.example.com/activate.php?email=" . $email . "&email_code=" . $email_code . "\r\n\r\n-- Example team");
}catch(PDOException $e){
die($e->getMessage());
}
}
Is there any kind souls out there can help me out on this? Letting me know where should I start and what should I do? Or the flow of the whole procedure in achieving my objectives.
Any help will be much appreciated! Thanks in advance.
Here is a example how to change your function to check if the user exist .. and which is the last index.
It is not pretty but will do the job and may be point you to the right ideas.
public function register($username, $password){
$password = sha1($password);
//check if the user exists and find first posible free index
$_username = $username;
if($this->db->query("SELECT * FROM `userinfo` WHERE `username` = 'user' ")){
$n = 1;
$max_index = 20;
while ($n < $max_index ) { //just to be safe
$_username = $username . $n;
if (!$this->db->query("SELECT * FROM `userinfo` WHERE `username` = '" . $_username . "' ")) {
break;
}
$n++;
}
if($n == $max_index){
die("Sorry ,there already (".$max_index.") entries of this username.");
}
}
//continue as normal just use $_username in the final query
$stmt = $this->db->prepare("INSERT INTO `userinfo` (`username`, `password`) VALUES (?, ?) ");
$stmt->bindValue(1, $_username, PDO::PARAM_STR);
$stmt->bindValue(2, $password, PDO::PARAM_STR);
try{
$stmt->execute();
// mail($email, 'Please activate your account', "Hello " . $username. ",\r\nThank you for registering with us. Please visit the link below so we can activate your account:\r\n\r\nhttp://www.example.com/activate.php?email=" . $email . "&email_code=" . $email_code . "\r\n\r\n-- Example team");
}catch(PDOException $e){
die($e->getMessage());
}
}
First of all you have to add a Sql-Wildcard like % _ * meaning see here to find all usernames they starts with "user" and have one or more charakter behind the "user"-string. Currently you only will get the username that excatly matchs the insert username.
But you could get some trouble by using the wrong wildcard, then
SELECT COUNT(id) FROM userinfo LIKE username = user%;
will always selct usernames like user1, user2, user3 but also something like userhorst..
To the pdo, the pdo help you to protect you system from sql injections. The prepare function sends only something like a query with wildcars for your parameter, thats means they send your statement without the parameters, to the Database. After this you send with the bindValue-function the single values to the Database. And finally you will excecute the statement. During this process the datapase can check each sended value for invalid signs.
Finally you have to check your if-statement. You will only get true when one user with the same name was in the database in all other cases (0,2,3,4,5,6,7) you get false.. But you want
if countUsers equal 0 then:
return false;
else
return true;
fi
Another part is you should thinking about using the sha1-hash, there are still better hashs to protect your passwords.
You can select all usernames like user* using:
SELECT username FROM `userinfo` WHERE username LIKE 'user%'
Next you should sort your results using asort:
asort($array_of_usernames);
then use substr or preg_match to get the number at the end of the username:
$number = substr($each_username, -1, 2) //within a foreach
Increment the number gotten then insert into database.
$new_username = "user" . $number++;
Thanks for the help guys!
Below are my current working code which I manage to tweak here and there based on the help given:
public function register($username, $password){
$stmt = $this->db->prepare("SELECT username FROM `userinfo` WHERE `username` LIKE :username");
$parse_username = "%".$username."%";
$stmt->bindValue(':username', $parse_username, PDO::PARAM_STR);
$stmt ->execute();
$user = $stmt->fetch();
$n = 1;
if($user){
$db_username = $user["username"];
$username_counter = preg_match("/".$username."(\d+)/", $db_username, $matches) ? (int)$matches[1] : NULL;
while ($n < $username_counter ) { //just to be safe
$new_username = $username . $n;
if (!$user) {
break;
}
$n++;
}
if($n == $username_counter){
$n++;
$new_username = $username.$n;
}
}else if(!$user){
$new_username = $username.$n;
}
$password = sha1($password);
$query = $this->db->prepare("INSERT INTO `userinfo` (`username`, `password`) VALUES (?, ?) ");
$query->bindValue(1, $new_username);
$query->bindValue(2, $password);
try{
$query->execute();
$_SESSION['new_username'] = $new_username;
// mail($email, 'Please activate your account', "Hello " . $username. ",\r\nThank you for registering with us. Please visit the link below so we can activate your account:\r\n\r\nhttp://www.example.com/activate.php?email=" . $email . "&email_code=" . $email_code . "\r\n\r\n-- Example team");
}catch(PDOException $e){
die($e->getMessage());
}
}
I am not sure that my way of coding is the best or professional, it is just based on my little logical knowledge of the flow. If there are any area where I can improve or rewrite, help me out if you wish to. =)
I've started a thread or two so far but nothing has got resolved. I'm not able to use the mysqlnd because i'm using a shared hosting account with godaddy.
All i need to do is check if my email address and/or username is in use; if they are in use throw and error, if not.. all is well.
Here is my code:
$input_errors = array();
if (!empty($_POST['username'])) {
$user = $_POST['username'];
} else {
$input_errors['username'] = "Must fill out username";
}
$email = filter_input(INPUT_POST, 'usermail', FILTER_VALIDATE_EMAIL);
if (false === $email) {
$input_errors['usermail'] = "Not a valid email address";
}
if(count($input_errors) > 0) {
print_r($input_errors); die();
}
$sql = "SELECT COUNT(*) as amount FROM people WHERE username = ?
OR email = ?";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("ss", $user, $email);
$stmt->execute();
$results = $stmt->get_result();
$data = mysqli_fetch_assoc($results);
if ($data['amount'] > 0)
{
print "User already exists";
}
}
else {
$stmt = $mysqli->stmt_init();
if (!$stmt) {
echo "Init failed";
} else {
$cmd = "INSERT INTO people (username, email, sign_up_date) VALUES (?, ?, NOW() )";
if ($stmt->prepare($cmd)) {
$stmt->bind_param('ss', $user, $email );
$stmt->execute();
echo $stmt->affected_rows . " row(s) inserted";
$stmt->close();
} else {
echo "Prepare failed";
}
mysqli_close($mysqli);
}
}
bind_result() does not work.
Change your sql statement to the following:
$sql = "SELECT COUNT(*) as amount FROM people WHERE username = '".mysqli_real_escape_string($_POST['username'])."' OR email = '".mysqli_real_escape_string($email)."'";