Currently working on a login script that would allow for multiple users with the same username to exist. The current plan is to generate a random "secret" user id that will take the place of the actual username. So how would I go about generating a random integer and checking to see if has been added?
This is my attempt at the code; however it does not seem to work as it does not seem to do anything.
$looptime = 100;
while ($looptime > 0) {
$userid = rand(0, 999999999);
$SQL = "SELECT * FROM Accounts WHERE username = '" . $userid . "'";
$result_id = #mysql_query($SQL) or die("DATABASE ERROR!");
$total = mysql_num_rows($result_id);
if (!$total) {
$looping = 0;
//CREATE THE ACCOUNT
mysql_query("INSERT INTO Accounts (id,username,password, email, money, activated) VALUES ('', '$username','$password', '$email', '0', '1')") or die("REGISTER ERROR!"); //1=account activated
//CONNECTED
echo "IMCONNECTED";
}
$looptime--;
}
EDIT: The code/number should be fairly easy to remember/jot down somewhere as the user will be able to view it and/or jot it down for account recovery purposes.
I would suggest either using a UUID/GUID (not an integer) to minimize the possibility of clashes, or using an identity column (not random) to guarantee uniqueness. Does it have to be an integer and does it have to be random?
Are you using an integer for the ID in the table? You could append this ID to the username. For example: MyUsername1234, MyUsername1245.
Here is a way you could do it. Create a scalar-variable function in your database (similar to below):
CREATE FUNCTION [dbo].[fn_randomNumber] (#guid nvarchar(128))
RETURNS int AS
BEGIN
SET #guid = REPLACE(#guid, '-', '');
DECLARE #idInt varchar(Max) = '';
DECLARE #i INT = 0;
DECLARE #char VARCHAR;
WHILE(#i < LEN(#guid))
BEGIN
SET #char = (SUBSTRING(#guid, #i, 1));
IF(ISNUMERIC(#char) = 1)
BEGIN
SET #idInt = #idInt + #char;
IF(LEN(#idInt) = 9)
BEGIN
BREAK;
END
END
SET #i = #i + 1;
END
RETURN CAST(#idInt as INT);
END
GO
Then execute this script:
SELECT [dbo].[fn_randomNumber] (
newid())
Of course you will want to evaluate the result to make sure it doesn't already exist.
Related
I am trying to write a serial and random PIN to mysql database but some PIN values are written multiple times.
how do I skip writing $pin into pin column if it already exist?
The snippet follows:
<?php
for($serial = 1000; $serial <= 1600; $serial++) {
$serial_prefix = "HCIS";
//generate random figures.
$rand_pin1 = rand(10599, 99999);
$rand_pin2 = rand(22222, 89898);
$pin = $rand_pin1 . $rand_pin2;
$f_serial = $serial_prefix . $serial;
$check = "SELECT pin FROM pin_serial WHERE pin = '$pin'";
$check_query = mysqli_query($connection, $check);
if(mysqli_num_rows($check_query) > 0){
// how do I skip writing $pin into pin column if it already exist here
}
elseif(mysqli_num_rows($check_query) == 0){
//inserting a generated figure and $serial into serial and pin column.
$pin_serial_query = "INSERT INTO pin_serial (serial, pin) VALUES('$f_serial', '$pin')";
mysqli_query($connection, $pin_serial_query);
}
}
Create unique index for pin column:
ALTER TABLE `pin_serial` ADD UNIQUE INDEX (`pin`)
Then change your query to
INSERT INTO pin_serial (serial, pin) VALUES('$f_serial', '$pin')
ON DUPLICATE KEY UPDATE serial_pin = VALUES(serial_pin)
(note ON DUPLICATE KEY UPDATE serial_pin = VALUES(serial_pin) part, this is just example, you can just pin=pin to skip) It will update query if row with that pin value already exists, or insert a new row.
You also can use INSERT IGNORE statement, which will just ignore duplicates.
More about INSERT in MySQL docs on topic
Please note that in your example, the script is vulnerable to Sql injection attack. To avoid it, you should first pass your parameters to mysqli_real_escape_string function to make the data inside sql-safe(by escaping ambiguous characters)
A do..while loop should solve your problem:
for ( $serial = 1000; $serial <= 1600; $serial++ ) {
$serial_prefix = "HCIS";
do {
// generate random figures
$rand_pin1 = rand( 10599, 99999 );
$rand_pin2 = rand( 22222, 89898 );
$pin = $rand_pin1 . $rand_pin2;
$f_serial = $serial_prefix . $pin;
$check = "SELECT pin FROM pin_serial WHERE pin = '$pin'";
$check_query = mysqli_query( $connection, $check );
} while ( mysqli_num_rows( $check_query ) >0 );
//inserting a generated figure and $serial into serial and pin column.
$pin_serial_query = "INSERT INTO pin_serial ( serial, pin ) VALUES ( '$f_serial', '$pin' )";
mysqli_query( $connection, $pin_serial_query );
}
While this will solve your immediate issue, as the number of rows grows you'll end up sending more and more SQL requests until you find an unused PIN. You will likely be happier with the result if you allow mySQL to generate a unique PIN for each new row.
if you want to write the serial into the row where the pin generated pin already sits (effectively overwriting the old serial that is already there, you would use an UPDATE statement:
... "UPDATE pin_serial SET serial='$serial'";
If you just want to skip this pin/serial combo I think yo already got the answer. Your code should work
I am trying to UPDATE my table using a PHP for loop but it will take too long to work. I really have 200,000 people in my table. When I open the php file, the browser literally hungs itself :) When I open the phpMyAdmin, I can see it works, yet very slowly.
Is there a way to do the exact same thing using SQL, directly in phpMyAdmin?
for ($a = 0; $a < 200000; $a++) {
$rand = mt_rand(10000000, 99999999);
// checks whether the same url exists or not
$sec = "SELECT person_url FROM person WHERE person_url = '$rand'";
$result = $sqli->query($sec);
$row = $result->fetch_assoc();
$finish = $row['person_url'];
if ($finish == false) {
$sql = $sqli->prepare("UPDATE person SET person_url = '$rand' WHERE person_id = '$a'");
$sql->execute();
}
}
You seem to be updating every row in your table with a random number in a particular range. You don't need to do any of the PHP processing at all.
You can simply update the table with
update person set person_url = (cast(rand()*89999999 as signed)+10000000);
You run the risk of getting duplicate entries in the person_url field which you will need to resolve by some means.
One means of doing this is to set the person_url column to unique and use the query with ignore and a different where clause:
update ignore person set person_url = (cast(rand()*89999999 as signed)+10000000)
where person_url is null;
This will probably do the job in one pass, but if it doesn't, run it repeatedly until it does. You'd be very unlucky to have to use more than two or three passes and it's still likely to be much faster than manually checking for uniqueness with PHP.
Prepare the statements outside the loop and use bound parameters.
$sql1 = $sqli->prepare("SELECT person_url FROM person WHERE person_url = ?");
$sql1->bind_param('s', $rand);
$sql2 = $sqli->prepare("UPDATE person SET person_url = ? WHERE person_id = ?");
$sql2->bind_param('si', $rand, $a);
for ($i = 0; $a < 200000; $a++) {
$rand = mt_rand(10000000, 99999999);
// checks whether the same url exists or not
$sql1->execute();
$sql1->store_result();
if($sql1->num_rows == 0) {
$sql2->execute();
}
}
I have a table (users) with various users. if you refer someone to register it creates a referal id in a field (refcode) similar to your (id) in his/her profile. now when he/she is logged in, i want to add value to the referal's profile.
So basically i need to add value to a user not logged in.
here is my code.
$sql="SELECT * FROM users";
$val=(2);
$result=mysql_query($sql,$bd);
$data=mysql_fetch_assoc($result);
while ($array = mysql_fetch_array($result)) {
// equate the value to a variable to use outside
// this while loop
$acc_balance = $array['com_balance'];
$comm = $array {$_SESSION['refcode']};
$commision = $array['id'];
}
$remainder = $acc_balance + $val;
$update_query = mysql_query("UPDATE users SET com_balance = '". mysql_real_escape_string($remainder) ."'
WHERE id=refcode");
if ($update_query) {
print ""
A bunch of changes, marked by numbers:
$sql="SELECT * FROM users where userID='$_SESSION['refcode']'"; //#1
$val = 2; //#2 : Why do u need the ()?
$result = mysql_query($sql,$bd);
$data=mysql_fetch_assoc($result);
while ($array = mysql_fetch_array($result)) {
// equate the value to a variable to use outside
// this while loop
$acc_balance = $array['com_balance'];
$comm = $array{$_SESSION['refcode']}; //#3: I am not sure what you're doing here?
$commision = $array['id'];
}
$remainder = $acc_balance + $val;
$update_query = mysql_query("UPDATE users SET com_balance = '". mysql_real_escape_string($remainder) ."'
WHERE id=refcode"); // #4: where are you defining refcode? if variable, the query needs to be WHERE id='$refcode'");
if ($update_query) {
print "Update successful";
Firstly, change:
$sql="SELECT * FROM users";
as you do not need to loop through an entire table just to get the details of the user logged in. Something like this should do the trick:
$yourID=3;// Assume this is sanitized data from a cookie or a login script.
$sql="SELECT * FROM users where userID=$yourID";
Secondly, when you verify the login of the user who referred the next user, just add in a query like this:
$update_query = mysql_query("
UPDATE users SET
com_balance = (select * from (
select com_balance from users where id=$yourID))");
This will update the new user with the balance from the referring user (which seems to be what you want). You will need to use the double subquery to get past the annoying mysql bug/feature where it cannot update a table from a subquery on the same table unless you encapsulate it in a second subquery.
I have a problem with integers in MySQL. I am trying to update a cell which stores an integer. However, I have problem with the type of that cell. Actually it is type is set to int but when I retrive the data I always get 0 and I belive it is because of the problem about how I am trying to get it. Here is my code sample;
function updateNumb($username) {
$query = "SELECT `num` FROM `profiles` WHERE `nick`='" . $username . "'";
$result = mysql_query($query, $this->conn) or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$row['num'] = $row['num'] + 1;
$numb = (int)$row['num'] + 1;
//here I update the data.
$query = "UPDATE `profiles` SET `num`=" . $numb . " WHERE `nick`='".$username."'";
mysql_query($query, $this->conn) or die(mysql_error());
return $numb;
}
Can it be because of mysql_fetch_array stuff? Or how could I overcome this problem?
replace partisayisi with num
There is nothing wrong with the code you provided, maybe it's not doing what you really need, for example num is incremented twice, but there are no visible mistakes that would make it return 0, at least not in what we can see.
Make sure you provide valid username, try to echo your query before sending to mysql to see what it really looks like, maybe try this query yourself in mysql client or phpmyadmin to see what's going on.
Also if the only thing you need is to increment num for some user you can do it in one update, you don't need to use select to get that number:
UPDATE profiles set num=num+1 WHERE nick='somenick'
I am creating a browser statistics script in PHP.
When PHP finds a match in a table how do I retrieve the row and pull all three fields of the table into separate variables.
My table rows are (browser, version, amount)
so I want to select everything from the TB were
browser = $browser and version = $version.
But when this happens how do I add one to the amount field and resubmit the row. Without altering anything else. Below is the code I have.
$browser_name= "MSIE";
$version = "7";
$query = ("SELECT * FROM $TB
WERE browser = '$browser_name' AND version = '$version'");
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count == 1)
{
$mysql = ("SELECT * FROM $TB
WERE browser = '$browser_name' AND version = '$version'");
//code to add 1 to amount would be here
}
else
{
//if browser is not detected insert fresh row.
$mysql = "INSERT INTO $TB (browser, version, amount)
VALUES ('$browser_name', '$version', 1)";
}
I have been looking around for answers for ages but they just tell me how to select information out of a DB as a whole.
update table set amount_field = amount_field + 1 where browser = '$browser_name' and version = '$version'
I don't understand why you make twice the same select.
$browser_name= "MSIE";
$version = "7";
$query = "SELECT * FROM $TB WHERE browser = '$browser_name' AND version = '$version'";
$result = mysql_query($query);
if($data = mysql_fetch_assoc($result))
{
print_r($data);
//use UPDATE from other answers if you need one here.
}
else
{
//if browser is not detected insert fresh row.
mysql_query("INSERT INTO $TB (browser, version, amount)
VALUES ('$browser_name', '$version', 1)");
}
Beware of SQL injections!
SELECT * FROM $TB WHERE browser
you have a mistake it must be WHERE instead of WERE.
You update query will be like this
UPDATE $TB SET ammount = 1 WHERE browser = $browser and version = $version
There are hundreds of issues with your query like sanitization etc. I suggest you read a good mySQL book to improve the queries. But to answer your question:
//code to add 1 to ammount would be here
mysql_query("update $TB set amount = amount + 1 where browser = '".mysql_real_escape_string($browser_name)."' and version = '".mysql_real_escape_string($version)."'");
First of all, you should connect to db using
$db = new mysqli('host','user','pass','dbname');
Then, your query isn't right. You have a sql syntax error.
SELECT * FROM table WHERE column = value
So, without prepare, your code should look like:
$tb = 'table_name'; // to avoid sql injections use addslashes() to your input
$browserName = addslashes('browser_name'); // like this
$version = '7';
$db = new mysqli('host','user','pass','dbname');
$result = $db->query("SELECT * FROM $tb WERE browser = '$browserName' AND version = '$version'");
// Than, you can fetch it.
while ($result->fetch as $row) {
echo $row['yourColumn']; // will display value of your row.
}
$db->query("INSERT INTO $tb (browser, version) VALUES ('$browser_name', '$version')";
}");
And, that's all. You can count your records using mysql count() method. Your code will work. I advice you, at first go to php.net and check the doc. There are many examples.