Check MySQL for duplicate entry [duplicate] - php

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 6 years ago.
I am modifying a web application that was built in PHP by another developer. Currently, if the user fills out a form and enters a username that is already being used, it displays the MySQL error Duplicate entry 'fred' for key 'username' on a new page. I want to make it so that an error message is displayed on the same page, so I'm trying to check if the username entered matches another username in the table, but I cannot get it to work. Any thoughts?
$username_entry = ($_POST['username']);
$username_match = mysql_query("SELECT * FROM business WHERE username='$username_entry'");
if (($_POST['username']) == $username_match ) {
// do something
}

first of all you're not returning anything from your query to check against. I query the db to see if any rows return with that username. $cnt is the number of rows so if that is greater than zero you have a duplicate.
$username_entry = ($_POST['username']);
$username_match = mysql_query("SELECT count(*) FROM business WHERE username='$username_entry'");
$cnt = mysql_num_rows($username_match);
if (($cnt > 0 ) {
// do something
}

Related

How to add randomize row values in php without repeatition [duplicate]

This question already has answers here:
Accessing random rows from database without repetition
(2 answers)
Closed 4 years ago.
from the past few days i have had this problem with a quiz scenario in created as part of my project. i wanted random questions to be asked but when i use the rand() function , the questions are being repeated. also i figured out that since its being done on the same page and every time the page refreshes, the random number is again selected thereby leading to this flaw! so i considered storing the value of the last random que_id in a session and generating a query like so:
enter code here <?php session_start();$jsqla=mysql_query("select que_id from mst_que");$jfeta=mysql_fetch_assoc($jsqla);session_start();$id=array($jfeta['id$_SESSION['id'][] = $id;$rs=mysql_query("SELECT * FROM `mst_que` WHERE que_id NOTIN ('id') ORDER BY RAND() ")
Please help me in this. I just want to create a session array where i want to store the previously generated random number and use it in query so that it is not repeated again. please
Store it in a variable and unset it from the array of questions:
function get_question($questions)
{
$question = rand($questions);
$questionKey = array_search($question, $questions);
unset($questions[$questionKey]);
return $question;
}
Try creating an array and then assign it to any session variable, for example:
$quizQuestions[] = $questionId;
$_SESSION['question'] = $quizQuestions;
In case you want to update the value, simply fetch it and assign new value and update it in the same variable again:
$quizQuestions = $_SESSION['question'];
$quizQuestions[] = $questionId;
$_SESSION['question'] = $quizQuestions;
Make sure that you have a session started first, add the following code to the very start of this script:
if(!isset($_SESSION)) {
session_start();
}

Generate random string variable and update MySQL field with it. [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I have a problem in that someone is using a bot to exploit my site. It would appear from logs that he is able to send multiple requests very quickly before the code is able to deduct the amount requested from his balance.
I had thought about stating a random value for every time it executes, which then gets put into his account row and compared against itself. This way it would be different every time its run.
Below is the head of the code:
$player=mysql_fetch_array(mysql_query("SELECT `id`,`time`,`ex`,`btc`,`string` FROM `players` WHERE `hash`='".prot($_GET['_unique'])."' LIMIT 1"));
$random = base64_encode(openssl_random_pseudo_bytes(10));
$setstring = $random;
mysql_query("UPDATE `players` SET `string` = $setstring WHERE `id`=$player[id] LIMIT 1");
$playersec=mysql_fetch_array(mysql_query("SELECT `string` FROM `players` WHERE `hash`='".prot($_GET['_unique'])."' LIMIT 1"));
if (!is_numeric($_GET['amount']) || (double)$_GET['amount']>$player['btc'] || (double)$_GET['amount']< 0 || $setstring != $playersec['string'] ) {
$error='yes';
$con=1;
}
I'm pretty sure this is the problem, as when it executes it doesn't put anything in thestring field i.e. it's left empty.
mysql_query("UPDATE `players` SET `string` = $setstring WHERE `id`=$player[id] LIMIT 1");
Yet when I run:
<?php
$random = base64_encode(openssl_random_pseudo_bytes(10));
$setstring = $random;
echo $setstring;
?>
It outputs fine with: IAXUqtKraNDb1Q==
Does anyone have any ideas?
Thanks
At this moment you are creating a work around. To prevent this kind of abuse, it is best to stop it at the root cause and to do that to use database transactions.
Steps:
1) Use INNODB
2) Use transaction encapsulation on php.
Update and retrieve your totals from the database. Since they are now in a transaction, the next transaction has to wait on the first, with as result that only the real available values can be retrieved.

is it possible to search a value in multiple columns using in clause in mysql?

I wonder if it is possible to search a value in columns using in clause having column names as in elements.
for instance :
$username_or_mail = 'value';
select * from users where $username_or_mail in(username,email);
where username and email are column names in table users.
I tried this and seems that it is working but i want to be sure if i'm right.
Would I be right in assuming you're using this for a "Enter your username or e-mail address and password to login" login form?
If so, then your SQL code is correct, but hints at a possible design flaw: what happens if someone has a username that is also the email address of another user? This could be used as a malicious attack (i.e. hijack another user's account by making your username equal to the victim's email address).
There is a solution/workaround: simply check for the '#' character and ensure that email addresses contain # and similarly ensure that no username contains # either.
...and if you're going to do that logic, then you might as well optimize the SQL and skip having to check multiple columns (psuedocode):
if( $usernameOrEmail contains '#' ) {
registerParameter("#email", $usernameOrEmail);
$sql = "SELECT ... WHERE EmailAddress = #email"; // note that "#email" is the syntax for query parameters in MySQL.
} else {
registerParameter("#userName", $usernameOrEmail);
$sql = "SELECT ... WHERE UserName = #userName";
}

PHP Retrieve Column In Lowercase [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
PHP PDO Username Availability Checker
I have a php script that checks the availability of a username (if it's taken already or not). But I want to compare the username typed in by the user and the usernames in the database in lowercase. I already put the input in lowercase, but how do I make the retrieved column in lower case. Here's the php script
<?php
$usr = strtolower($_GET['username']);
$link = new PDO('mysql:host=***;dbname=***;charset=UTF-8','***','***');
$usr_check = $link->prepare("SELECT * FROM Conference WHERE Username = :usr");
$usr_check->bindParam(':usr', $usr);
$usr_check->execute();
if($usr_check->rowCount()>0)
echo "false";
else
echo "true";
?>
How do i set the username column to lowercase, then compare it to $usr? Thanks
please try
SELECT * FROM Conference WHERE LOWER(Username) = :usr
http://www.sqlinfo.net/mysql/mysql_function_upper_lower.php
ok as you said on the comment below I recommend you to do the following.
convert your result into lowercase http://sqlfiddle.com/#!2/bd50e/1
convert your comparison string to the table into lowercase by using strtolower
now compare the results
You could use
SELECT * FROM Conference WHERE LOWER(Username) = :usr
as the query, but that would cost you the benefit of an index.
However, the comparison should be case insensitive anyways if the column uses a "ci" collation.
If you want to convert string to lower in MySQL use LOWER(str) function.

Basic Login Script using php and mysql inquiry

Attempting to write a check for a login script to see if the username is available.
Would the best way to write this query be to check
if isset(!_POST[]) for both values (nick and pass)
then connect to database
WHERE the mysql database for the usernick requested
return the user id if the usernick exists
evaluate if isset($id) to see if the user name is taken
and use that to continue to creating an entry
Does this logically sound like a method to check for login without using excessive code
sorry for not posting the code, it is on another computer and this computer is locked down by my administrator at work...
Also, is there another way to evaluate if a value exists in the database?
For instance, instead of setting $id to the return value of the mysql database can i just ping the mysql database for the information and have it return a Boolean result so I am not putting out any user information.
Thanks,
Matt
You can do :
SELECT NULL FROM <Table> WHERE <Conditions>
When you run your query, if you get a row/rows, then your condition is met, if you get 0 rows, then they don't (therefore whatever you are looking for does not exist).
As Boris mentioned, do not forget to sanitize your inputs.!
What this query is supposed to do, is return rows with a NULL value, if what you were looking for in your criteria is met. That is, for example you do :
SELECT NULL FROM Users WHERE Name = 'something';
And you get :
| NULL |
1 row(s) returned.
It means that a user with that name exists, in the other hand you would get:
0 rows returned.
That means it does not exist.
In PHP you could easily use mysql_num_rows($result) to test for this, if you get 0 rows then your user does not exist.
This is of course only useful if you are JUST testing the existance of something, if you actually need the information, you need to do a normal query.
You can just SELECT username WHERE username LIKE $username (don't forget to sanitize and filter $username before to use it in a query).
Then use $result = mysql_fetch_array($query); and count($result);
If count($result) is equal to 0 or null, then, there is no such username in database.
Try this.
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * from <table name> WHERE username = $username AND password = $password", $connection);
$row = mysql_fetch_array($result);
if(mysql_num_rows($row) == 1) //assuming username, password pair is unique
echo "Login Successful";
else
echo "Login Unsuccessful";

Categories