How to create username unique with respect to database? [duplicate] - php

This question already has answers here:
How to prevent duplicate usernames when people register?
(4 answers)
Closed 2 years ago.
I have one field named
username:_________
now i want to add manuaaly username to the database
if once added and i add same next time it must automatically show invalid username right side of textbox i am searching same code on net and tried too many solution but not working.
This i want to performed in php and mysqli

Just mark it as UNIQUE.
CREATE TABLE User
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
And in PHP script do something like this:
$query = mysqli_query($con, "SELECT id FROM user WHERE username='$username'");
if(mysqli_num_rows($query) > 0){
echo "Username already exists";
}else{
// do something
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
}
And if you want to check in realtime if username is available (like #Arun pointed) maybe this would help a bit.

Related

how to check for duplicate entry before update in php + mysql? [duplicate]

This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 1 year ago.
check for duplicate "username" field
case :
if user wants to update record other than username field (like firstname or whatever) and i used simple select query to check for duplicate like
"SELECT * from user where username = $username"
and check count than it will return count 1 because user name already exist (in same record)
case :
if user change username (it is unique now) and check for duplicate using same query than it returns 0 and it works fine
so if user doesn't change username than query above breaks
so i changed query like:
"SELECT *
FROM user
WHERE `username` = $username
AND user_ID != $uid" (here user_ID is primary key)
so it will not check current record so, is it correct or not ?
EDIT :
my project is based on mvc ,modal have global function like
insert($tablename,$condition)
update($tablename,$condition)
Etc
and update funciton works like
create sql query (dynamically based on $condition)
Execute query with $result = $query->execute();
and
if ($result) {
$msg = 'true';
} else {
$msg = 'false';
}
$data = array(
'result' => $msg,
'query' => $sql,
'eventType' => 'Update'
);
return $data;
so how can i catch duplicate entry exception (i mean on which colum it occured (when multiple unique key exist))
The best way to do SQL is to have the structure enforce the contrants:
If you want a unique user name, declare a unique key on it.
ALTER TABLE user ADD UNIQUE KEY username_uniq(username)
Don't try to detect it up front, that will always be subject to race conditions.
Catch the duplicate key error exception when and UPDATE/ INSERT is done which violates the constraints.

How to properly retrieve unsigned bigint from MySQL column with PHP? [duplicate]

This question already has answers here:
Display binary(16) column as hex in mysql
(4 answers)
PHP mysql bigint issue
(3 answers)
Closed 2 years ago.
I'm not sure if it's PHP or MySQL that's messing me up.
Say, I have a table with BIGINT UNSIGNED column (let's name it flgs). I read data from that table with PHP as such:
$query = "SELECT * FROM `$tbl_nm` ORDER BY `$colID` ASC";
$res = mysqli_query($link, $query);
if($res)
{
while($aRow = mysqli_fetch_assoc($res))
{
echo("flags=0x".dechex($aRow['flgs'])."<br>");
}
}
if the flgs column has value with bit-63 reset, then I get the correct result. But if bit-63 is set, the return value is 0x7fffffffffffffff. Hmmmm?
For instance, if flgs is set to 0x8000000000000000 in the database, my code above prints:
flags=0x7fffffffffffffff
Why, PHP, why?

how to restrict registered user from trying to vote again [duplicate]

This question already has an answer here:
how to restrict registered user from trying to vote twice [closed]
(1 answer)
Closed 6 years ago.
I'm very new to php coding and website designing.
I'm trying to develop an online voting system, where registered users only, are allowed to vote. I have done everything and it's working fine, but the help I need is after the user have logged out, how can I make the user not to be able to login again and vote twice? Or how I can I redirect the user the second time?
You can manage the user by taking the field in the database table. By applying the condition on that field at the time of login you will able to restrict the user who had already given the vote.
Well this is not that difficult to achieve if you had really had given a thought you would have seen how easy it is.
your users table must have a unique ID for the user to identify the user, then also on your table columns you need to have an enumerated field, you can call it votingstatus and set its default value to a, then when the user successfully casts a vote you then updated that field to bthen you can look the the form controls for all users with votingstatus = b in that way you won't allow any one with b status to vote. when the user login you need to check the votingstatus if the user have a then allow login, if its b return appropriate message and deny access.
Example table
CREATE TABLE `voters` (
`voter_id` int(6) NOT NULL,
`id_number` varchar(255) NOT NULL,
`firstname` varchar(255) DEFAULT NULL,
`lastname` varchar(255) DEFAULT NULL,
`email` varchar(255) NOT NULL,
`voting_status` enum('a','b') DEFAULT 'a',
`password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Example casting a vote
<?php
try {
$dbh->beginTransaction();
$stmt = $dbh->prepare("UPDATE candidates set votes = votes + 1 where candidate_Id = ? ");
if ($stmt->execute([$selectedvoter])) {
$update = $dbh->prepare("UPDATE voters set voting_status = 'b' where voter_id = ?");
$update->execute([$_SESSION['voter']]);
$dbh->commit();
echo "<p class=\"alert alert-success\">Vote Casted</p>";
}else{
echo "<p class=\"alert alert-danger\"> could not cast Vote</p>";
}
}
catch (PDOException $e) {
error_log("Error : " . $e->getMessage());
}
?>
Login :
try {
$stmt = $dbh->prepare("SELECT voter_id,id_number,password from voters where id_number = ? AND voting_status = 'a' ");
$stmt->bindValue(1,$username);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0){
foreach($results as $row){
if(password_verify($password,$row['password'])){
$SignError="<div class=\"alert alert-success\">
<button class=\"close\" data-dismiss=\"alert\">x</button>
Login Success. Redirecting...
</div>";
header("refresh:4;url=page.php"); // change page to ur dashboard url
}else{
$SignError="<div class=\"alert alert-error\">
<button class=\"close\" data-dismiss=\"alert\">x</button>
Password and ID number does not match
</div>";
}
}
}else{
$SignError="<div class=\"alert alert-error\">
<button class=\"close\" data-dismiss=\"alert\">x</button>
Password and ID number does not match
</div>";
}
} catch (PDOException $e) {
error_log($e);
}
The login code only allow voters with voting_status = a (meaning users who did not vote yet)

How to delete particular columns data in database using php mysql [duplicate]

This question already has answers here:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 answers)
Closed 7 years ago.
Hi iam trying to delete certain columns data from database.Here is my code for delete query.
//getting column id by comparing the id need to delete the data from that row.
$id=$_GET['id'];
$res = "DELETE rental_annual_rent,
rental_block,
rental_street,
rental_area,
rental_town,
rental_state,
rental_pincode
FROM house_details
WHERE house_details_id='$id'";
$result=mysql_query($res);
if(mysql_affected_rows()){
echo "successfully deleted";
session_start();
header("Location:property.php");
}else{
echo "Failure";
}
First iam inserting house_details data into database but i need to delete only particular data from that columns
What you want is an UPDATE, not a DELETE since you want to keep the row, but just clear/blank/unset certain columns within the row.
$res = "UPDATE house_details SET
rental_annual_rent = NULL,
rental_block = NULL,
rental_street = NULL,
rental_area = NULL,
rental_town = NULL,
rental_state = NULL,
rental_pincode = NULL
WHERE house_details_id='$id'";
Note that you should really be sanitizing your id input before using it in the query, you should parameterize it, and you should also migrate from the mysql library to mysqli or PDO

what is the wrong with this query?

I have a problem with this query and hope someone will help me to fix this. I am trying to check username and email address are available to register when registering a new user to my site. username is coming from login table and email address is coming from contact table. Now I need to make a query to check given username and email by new users are available to register. If those are not available I want to print error messages. I am trying to make this query something like this but its not working as I expect.
$q = "SELECT username, email FROM login
INNER JOIN contact
WHERE login.username = '$username' OR contact.email = '$email'";
Then I am checking this query in PHP like this
$r = mysqli_query ($dbc, $q);
// Get the number of rows returned:
$rows = mysqli_num_rows($r);
if ($rows == 0) { // No problems!
// register new user
} else { // The email address or username is not available.
if ($rows == 2) { // Both are taken.
$reg_errors['email'] = 'This email address has already been registered.1';
$reg_errors['username'] = 'This username has already been registered.2';
} else { // One or both may be taken.
// Get row:
$row = mysqli_fetch_array($r, MYSQLI_NUM);
if( ($row[0] == $_POST['email']) && ($row[1] == $_POST['username'])) { // Both match.
$reg_errors['email'] = 'This email address has already been registered.3';
$reg_errors['username'] = 'This username has already been registered with this email address.4';
} elseif ($row[0] == $_POST['email']) { // Email match.
$reg_errors['email'] = 'This email address has already been registered.5';
} elseif ($row[1] == $_POST['username']) { // Username match.
$reg_errors['username'] = 'This username has already been registered.6';
}
} // End of $rows == 2 ELSE.
my problem is PHP script always going to this code. query not checking individually username and email. I trying something like this.. username not available and email available, email not available and username available. But always going to this
if ($rows == 2) { // Both are taken.
$reg_errors['email'] = 'This email address has already been registered.1';
$reg_errors['username'] = 'This username has already been registered.2';
}
EDIT: Table structure..
# --------------
# Login Table
# --------------
CREATE TABLE login (
login_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(80) NOT NULL,
password VARBINARY(32) NOT NULL,
PRIMARY KEY (login_id),
UNIQUE(username)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
# --------------
# Contact Table
# --------------
CREATE TABLE contact (
contact_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
telephone VARCHAR(60) DEFAULT NULL,
mobile CHAR(10) NOT NULL,
email VARCHAR(80) DEFAULT NULL,
PRIMARY KEY (contact_id),
UNIQUE (email)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
You must provide ON clause which define the relationship on how the two tables are related with each other.
SELECT username, email
FROM login
INNER JOIN contact
ON login.colname = b.colName // change to your orignal colName
WHERE login.username = '$username' OR
contact.email = '$email'
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
An alternative way to do this without checking on the value on the tables is by enforcing UNIQUE constraints on column of the table, ex
ALTER TABLE login ADD CONSTRAINT tb_uq UNIQUE (username);
ALTER TABLE contact ADD CONSTRAINT tb_uq1 UNIQUE (email);
when the two alter statements has been successfully executed,you cannot insert value if it already exists on that column.
UPDATE 1
SELECT COUNT(*)
FROM
(
SELECT userName as Value FROM Login
UNION
SELECT email as Value FROM contact
) s
WHERE VALUE IN ('$username','$email')
if the query above will return greater than 0, it means that value(s) already exists.
UPDATE 2
SELECT *
FROM
(
SELECT userName, NULL AS email FROM Login
UNION
SELECT NULL AS username, email FROM contact
) s
WHERE username = '$username' OR email = '$email'
Currently, your query selects every row from both tables as long as there is a single match for one or the other. You can get matching rows from both tables simultaneously:
SELECT username FROM login WHERE username = '$username'
UNION ALL SELECT email FROM contact WHERE email = '$email'
...and also with separate queries.
Your queries are vulnerable to SQL injection.
You are really checking 2 different things. A single query doesn't make sense, at least not a join. I suggest union instead:
select 'username' as exists from login
where username = '$username'
union all
select 'email' as exists from contact
where email = '$email'
This will return a table with a column called exists and a row for each element that exists. Here is what you would get back if both username and email exist:
EXISTS
username
email
Where you run this query, you already know what the username and email they entered are, so there is no point in returning those values from the table.
As others have pointed out, you have a big security hole if $username and $email are being passed in directly from the user. You definitely have to handle that somehow.
Every Inner join clause needs to have a predicate or "ON" condition to specify the rule or rules to be enforced when Joining the two tables...
the query needs an "ON" clause after the Inner Join. I'm not sure what that condition should be, but, as an example....
$q = "SELECT username, email FROM login
INNER JOIN contact
On contact.username = login.userName
WHERE login.username = '$username' OR contact.email = '$email'";
your join have a problem , because you should determine column wich you want join on it!
for example
NNER JOIN contact
On contact.id= login.contactId

Categories