I am a bit stuck with my code.
I am practising and would like to achive the following.
Before an user sign up, i want to check the users username exists, if exists than increase the name by one.
So my logic works like this. User gives his/her first and last name, generates an username based on that.
function
function unique_name($first_name, $last_name) {
$username = strtolower($first_name.'.'.$last_name)
$check = mysqL_query(" SELECT username WHERE username = '".$username."' ");
if(count($check == 1)) {
$i = 2;
foreach($check as $user) {
return $user['username'].$i;
$i++;
}
} else {
return $username;
}
}
$username = unique_name($_POST['first_name'], $_POST['last_name']);
// saveing the increased username
So actually the script should check if the generated unique username exsits if exsits increase, and encrease it even if it exsits with a number
example
Tom Anderson signs up, username will be tom.anderson, saved as tom anderson
Second Tom Anderson signs up, username will be tom.anderson, it already exists, save the new one as tom.anderson2.
The third user signs up he is tom anderson too, username tom.anderson* exsits twice, increase to tom.anderson3.
So i dont have a problem checking if the user exsits and saveing it, my problem is, how to increase every username if exist?
I am not asking anybody to write this for me i am nust looking for a hint
Thank you
EDIT
Thank you for the replies but this does not work
if(count($check) == 1) {
$i = 2;
foreach($check as $user) {
return $user['username'].count($check);
$i++;
}
} else {
return $username;
}
This only check the username with out a number, so if username tom.anderson exists it increases to tom.anderson1 but if tom.anderson1 exists too it wont increase to tom.anderson2
Can you have something that just appends the count of the rows returned, unless it's 0?
if(count($check) > 0) {
return $user['username'].count($check);
} else {
return $username;
}
change the SQL:
" SELECT username WHERE username LIKE '".$username."%' "
Try to give like this
if(count($check) == 1) {
$i = 2;
foreach($check as $user) {
return $user['username'].count($check);
$i++;
}
} else {
return $username;
}
You may add new field into user table, and called it base_username.
Them fetch count rows with given username, and increase every username on count found
Something like this
`function unique_name($first_name, $last_name) {
$unique_name = $username = strtolower($first_name.'.'.$last_name)
$cnt = get_row(" SELECT COUNT(*) from `users` WHERE base_username = '".$username."' LIMIT 1 ");
if($cnt){
$unique_name = $username . $cnt + 1;
}
return $unique_name;
}`
Related
I'm creating a CRM where I want to assign coaches to members on signup. I'm struggling to find a logic for the below scenarios.
1) At the moment we have 50 users and 5 coaches.
2) We want to assign coach 1st to user 1st, coach 2nd to user 2nd and so on.
3) Coach 1st will then assigned to user 6th. By using this approach each coach will get equal users.
I'm using below code to achieve it, it works for me, but I don't know how reliable is this.
static function getACoach($userId) {
$totalCoach = 5;
if($userId > $totalCoach) {
$coachId = $userId % $totalCoach;
} else {
$coachId = $userId;
}
}
Thank you!
This simple approach worked for me.
function getACoach($userId) {
$totalCoach = 5;
if($userId > $totalCoach) {
$coachId = $userId % $totalCoach;
} else {
$coachId = $userId;
}
return $coachId;
}
Thank you!
I have strings of usernames in array . I want to generate a unique string of username which do not exits in array.(probably with some numbers following the username)
How do I achieve this?
I have summarize the code:
function generate_unique_username(){
$firstname = "james";//data coming from user
$lastname = "oduro";//data coming from user
$new_username = $firstname.$lastname;
$usersnames = array("james39","oduro32","kwame93","elvisasante","frimpong32","edward32","jamesoduro");
//Loop through ARRAY usernames and check elements against VAR $new_username
if (in_array($new_username, $usersnames)) {
//generate new username which is not inside array
//the new generated string should also be check against array to ensure is doens not exit.
}else{
return $new_username;
}
}
Thank you.
Generating username from the stored array is not a good practice, I would suggest you to use the database.
If you are using the database instead of the array, you can use the best method to generate the unique username as following:
function generate_unique_username(){
$firstname = "james";//data coming from user
$lastname = "oduro";//data coming from user
$new_username = $firstname.$lastname;
/* Note: writing here pseudo sql code, replace with the actual php mysql query syntax */
$query = "SELECT COUNT(id) as user_count FROM user WHERE username like '%".$new_username."%'";
$result = mysql_query($query);
$count = $result['user_count'];
if(!empty($count)) {
$new_username = $new_username . $count;
}
return $new_username;
}
I think in this case you should first off try and assign cooler user names to the users then when that fails you go for a number suffix. This is an approach I may use. You may need to change the code to your more preferred and secured mysqli call like using the PDO or MySQLI prepared statement.
//function that will be used to figure out if the user name is available or not
function isAvailable($userName){
global $mysqli;
$result = $mysqli->query("SELECT id FROM users WHERE user_name='$userName'") or die($mysqli->error());
// We know username exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {
//echo 'User with this username already exists!';
return false;
}else{
return true;
}
}
function generate_unique_username($firstname, $lastname, $id){
$userNamesList = array();
$firstChar = str_split($firstname, 1)[0];
$firstTwoChar = str_split($firstname, 2)[0];
/**
* an array of numbers that may be used as suffix for the user names index 0 would be the year
* and index 1, 2 and 3 would be month, day and hour respectively.
*/
$numSufix = explode('-', date('Y-m-d-H'));
// create an array of nice possible user names from the first name and last name
array_push($userNamesList,
$firstname, //james
$lastname, // oduro
$firstname.$lastname, //jamesoduro
$firstname.'.'.$lastname, //james.oduro
$firstname.'-'.$lastname, //james-oduro
$firstChar.$lastname, //joduro
$firstTwoChar.$lastname, //jaoduro,
$firstname.$numSufix[0], //james2019
$firstname.$numSufix[1], //james12 i.e the month of reg
$firstname.$numSufix[2], //james28 i.e the day of reg
$firstname.$numSufix[3] //james13 i.e the hour of day of reg
);
$isAvailable = false; //initialize available with false
$index = 0;
$maxIndex = count($userNamesList) - 1;
// loop through all the userNameList and find the one that is available
do {
$availableUserName = $userNamesList[$index];
$isAvailable = isAvailable($availableUserName);
$limit = $index >= $maxIndex;
$index += 1;
if($limit){
break;
}
} while (!$isAvailable );
// if all of them is not available concatenate the first name with the user unique id from the database
// Since no two rows can have the same id. this will sure give a unique username
if(!$isAvailable){
return $firstname.$userId;
}
return $availableUserName;
}
//Get the unique user id from your database, for now let's go with 30
$userId = 30;
echo generate_unique_username('john', 'oduro', $userId);
Also, it would be nice to provide a fallback feature where the user can change their user name to any other unique value, in case they do not like the auto-generated value.
I am working on a function that allows a user to up vote a post no more than one time. There are multiple posts on a page so I need to keep track of which posts the user has voted on.
I do that by keeping a total sum of the votes casts. For instance, if a user up votes a post, they should be remove their vote by down voting once, or change their original up vote to a down vote by down voting twice.
The first time a vote is cast, I initialize the $_SESSION variable to 0. A down vote takes it to -1 and an up vote takes it to 1.
Here is the PHP function for up vote (the down vote function is similar):
function upVote($post_id) {
global $databaseController;
if(!isset($_SESSION[$post_id])) {
$_SESSION[$post_id] = 0;
}
if($_SESSION[$post_id] <= 0) {
$sql = "SELECT likes FROM posts WHERE id='" . $post_id . "'";
$results = $databaseController->select($sql);
if($results && $results->num_rows == 1) {
$results = $results->fetch_assoc();
$new_likes = ++$results['likes'];
try {
$databaseController->startTransaction();
$sql = "UPDATE posts SET likes=" . $new_likes . " WHERE id=" . $post_id;
$databaseController->update($sql);
if($databaseController->commit()) {
$_SESSION[$post_id] = ++$_SESSION[$post_id];
return true;
}
} catch (Exception $e) {
$databaseController->rollback();
return false;
}
}
}
return false;
}
The $_SESSION[$post_id] is always being reset to 0 each time the function is called allowing the user to vote as many times as they want.
Why is this happening? It seems to me that the variable should only be set to 0 if the user has never voted on the post, else it just pulls up the variable, sees that it exists, and modifies it.
Is there anything wrong with my logic? Or am I not using $_SESSION variables in the correct way?
I would like to create a random string for every row in my row for the field password - basically its a bulk password generator.
Unfortunately, when I hit the bulk reset button the passwords are reset to all the same string. I would like to have a different random string for each row.
Here is my code:
echo '<form method="post" action=""><input type="submit" name="bulk_password_reset" value="Bulk Password Reset" /></form>';
if (isset($_POST['bulk_password_reset'])) {
$password = generateRandomString();
while ($result = $sqlUpdate->fetch()) {
$sqlUpdate = $dbh->prepare("UPDATE $tableName SET password = :password");
$sqlUpdate-> execute(array(':password'=>$password));
$sqlUpdate->execute();
header('Location: su_password_reset.php');
}
}
Here is my random string generator function:
//Generate random password
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
What am I doing wrong please?
You should place $password = generateRandomString(); inside while loop, and also add WHERE condition (I assume, you have id in your table) to apply each UPDATE to only one row.
$sqlSelect = $dbh->query("SELECT id FROM $tableName"); // select ids where you want to change passwords
while ($result = $sqlSelect->fetch()) {
$password = generateRandomString();
$sqlUpdate = $dbh->prepare("UPDATE $tableName SET password = :password WHERE id = :id");
$sqlUpdate->execute(array(':password'=>$password, ':id'=>$result['id']));
header('Location: su_password_reset.php');
}
UPD I am no pretty sure about syntax, but this gives you an idea, what you need to do (select id for each row, generate password, then update password for this row only).
This seems to be the problem:
UPDATE $tableName SET password = :password
You aren't specifying a WHERE clause in your UPDATE statement, so it is being applied to the entire column rather than a specific row.
Move this inside your while loop:
$password = generateRandomString();
Currently you're calculating the $password just once, then using that value for every row.
Additionally, your UPDATE clause isn't restricted to any matching criteria. Each cycle through the loop, you're updating every row in the table. You need to add a WHERE clause to restrict the update to that particular row.
Try moving your $password = generatRandomString() inside your while loop
while ($result = $sqlUpdate->fetch()) {
$password = generateRandomString();
$sqlUpdate = $dbh->prepare("UPDATE $tableName SET password = :password");
$sqlUpdate-> execute(array(':password'=>$password));
$sqlUpdate->execute();
header('Location: su_password_reset.php');
}
<?php
$password = generateRandomString(); // Move this inside your while loop
while ($result = $sqlUpdate->fetch())
{
$password = generateRandomString(); // Like so...
}
// Change function generateRandomString($length = 10) {...} to...
function generateRandomString()
{
return md5(rand().time());
}
And add a where clause to your update query.
I've got small problem checking the duplicate email, I don't know what I've done wrong.
PHP SIDE:
// convert to lower case
$email = $db->real_escape_string(trim(strtolower($_POST['email'])));
$q = $db->query("SELECT email FROM user WHERE email='$email'");
$r = $q->fetch_assoc();
if($email == $r['email']) {
echo 'yes';
} else {
echo 'no';
}
I've got an old record in the database. Some of the emails come mixed with uppercase and lowercase! And most of them are from hotmail email account! How to check email that even contain lower and uppercase?
ie: Donald1990#hotmail.com // it skips the duplicate error?
Hedmunds#hotmail.co.uk
hedmunds#hotmail.co.uk
Actually I think you want
"SELECT LOWER(email) FROM user WHERE LOWER(email)='$email'"
i am using laravel 5, but the concept is same
//check from 1 to 500 records, some DB will timeout if 1 to 5000 or more depends on amount of Data, you may have to increase the timeout limit
$users = Subscribers::all(); // take all users from DB
for ($x = $check_from; $x <= $check_to; $x++){
$check_user = Subscribers::select('id','email')->where('id',$x)->first();
if (!isset($check_user)){ // check for gaps in betw records
echo $x . "- not set<br>";
}
else{
$check_user_id = strtolower(trim($check_user->id));
$check_user_email = strtolower(trim($check_user->email));
foreach ($users as $user){
$user_id = strtolower(trim($user->id));
$user_email = strtolower(trim($user->email));
if ($check_user_email == $user_email AND $check_user_id !== $user_id ){
echo $check_user_id.' - '.$user_id.' - '. $user_email.' - Duplicated records<br>';
//$user->delete();
// choose to delete duplicate or whatever u wanna do with it
}
}
}
}
// need to check email is equal && user_id is not same, then there will be 2 id with same email
My code works but if someone can improve to make it shorter will be better.