Check name is unique if not append - php

My application requires the user to enter their business name, which the application will automatically create into a unique identifier to be used in URLs, ie
"Bob's Cafe" will become "bobs-cafe"
But if there are duplicate names I would like the application to add a number so if there is already a "bobs-cafe" we will use "bobs-cafe-1" and likewise if there is already a "bobs-cafe-1" we will use "bobs-cafe-2"
Ive used explode and also looked at a regular expressions but I dont know the best way to approach this.
Im stuck in being able to grab the number and incrementing it and returning the string

Adding to Sarfraz's answer, you might want to find it using a LIKE statement
SELECT `urlIdentifier` FROM `businesses` WHERE `urlIdentifier` LIKE `bobs-cafe%`
which will get all the bobs-cafe items - that way, if you get 5 rows you know you have
bobs-cafe
bobs-cafe-1
bobs-cafe-2
bobs-cafe-3
bobs-cafe-4
and that you'll need to add bobs-cafe-5
EDIT - Or this:
SELECT count(*) as `howMany` FROM `businesses` WHERE `urlIdentifier` LIKE `bobs-cafe%`
Now your result object ( or array ) will have the total number:
echo $resultObject->howMany; // number of bobs-cafe sql found

Why not to add an autoincrement number to every identifier in the URL?
Just like SO does:
stackoverflow.com/questions/2895334/php-application-check-name-is-unique-if-not-append
so, you have both unique identifier and a business name.
This is even better because they are free to change their business name, without changing an identifier.
As for your question it's very simple. Just for the PHP practice:
if (/* you've found the name is already non unique and have the max one in the $id */) {
$parts = explode("-",$id);
if (isset($parts[1])) $newid = $parts[0]."-".($parts[1]+1);
else $newid = $parts[0]."-1";
}

Assuming $user is already in the form bobs-cafe
function username_exists ( $user ) {
$result = mysql_query("SELECT name FROM table WHERE $name LIKE '$user%' ");
$count = mysql_num_rows($result);
if ( $result ) {
$num = $count+1;
return username_exists ( $user.'-'.$num ) ;
} else {
return $user;
}
}

Related

Compare integer inside url in database

I have the following rows in the database inside url column:
http://some_url/something/34123122.json
http://some_url/something/53124322.json
http://some_url/something/22214322.json
And I want to retrieve them in some function, like this (pseudocode):
function retrieve($ids) {
return $this->fetchAll("SELECT * FROM table WHERE url IN $ids");
}
The problem is that $ids parameter MUST BE an array with ids from those urls only, like:
array(
[0] => 34123122
[1] => 22214322
)
So I have to do something in this function so that I can retrieve rows with urls that contain those ids. How can I do that? Urls can change, but the /******.json ending has always the same pattern.
I don't want to make another query selecting the beginning of the url, it will slow down the application too much.
The proper way to do this is to query only the part of the data that you are interested in - the number. So, you receive an instant +10 to intelligence from performing a quest nearby and you determine that you could create another column to save that number. Your table looks like this now:
CREATE TABLE mytable (
id int not null auto_increment,
url varchar(255) not null,
json_number int not null,
PRIMARY KEY(id),
INDEX(json_number)
) ENGINE = InnoDB;
Before inserting into the table, you use integer sanitizing filter to extract the number from the URL without wasting too much time
Given a URL like this: http://some_url/something/34123122.json you can easily extract the number like this:
$url = 'http://some_url/something/34123122.json';
$number = filter_var($url, FILTER_SANITIZE_NUMBER_INT);
echo $number; // echoes 34123122
And now your query is trivial, you check the json_number column which is also indexed at the same time.
Naturally, you can ignore all I wrote and try other answers which are ugly hacks and worst of all - they're all full table scans.
you will have to use regex in mysql, change your function:
function retrieve($ids) {
$regex = '('.implode('|', $ids).').json$';
return $this->fetchAll("SELECT * FROM table WHERE url REGEXP '$regex'");
}
Note: this is not an optimal solution for large tables. I would suggest you to create an id field in your table and if all ids are unique then you can make id a primary key. Also whenever you insert in that table take out the id part from url and insert it into the id field. In that way you can skip regex. If you are willing to create an id field, then you can execute the following query to update your current table id field:
mysql> update your_table_name set id=replace(substring_index(url, '/', -1), '.json', '');
I do not know if this is a neat solution, but it should work.
function getData($ids) {
foreach($ids as $item) {
$str[] = $item . ".json";
}
$where = "";
foreach($str as $item) {
$where .= "url LIKE '%$item' OR ";
}
return substr("SELECT * FROM table WHERE " . $where, 0, -4);
}
$ids = array(34123122, 53124322, 22214322);
echo getData($ids);
Result:
SELECT * FROM table WHERE url LIKE '%34123122.json' OR url LIKE '%53124322.json' OR url LIKE '%22214322.json'
I think this should do it. Of course you have to run the query aswell.

writing a second query based on results of the first - Not working

*MySQL will be upgraded later.
Preface: Authors can register in two languages and, for various additional reasons, that meant 2 databases. We realize that the setup appears odd in the use of multiple databases but it is more this abbreviated explanation that makes it seem so. So please ignore that oddity.
Situation:
My first query produces a recordset of authors who have cancelled their subscription. It finds them in the first database.
require_once('ConnString/FirstAuth.php');
mysql_select_db($xxxxx, $xxxxxx);
$query_Recordset1 = "SELECT auth_email FROM Authors WHERE Cancel = 'Cancel'";
$Recordset1 = mysql_query($query_Recordset1, $xxxxxx) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
In the second db where they are also listed, (table and column names are identical) I want to update them because they cancelled. To select their records for updating, I want to take the first recordset, put it into an array, swap out the connStrings, then search using that array.
These also work.
$results = array();
do {
results[] = $row_Recordset1;
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
print_r($results);
gives me an array. Array ( [0] => Array ( [auth_email] => renault#autxxx.com ) [1] => Array ( [auth_email] => rinaldi#autxxx.com ) [2] => Array ( [auth_email] => hemingway#autxxx.com )) ...so I know it is finding the first set of data.
Here's the problem: The query of the second database looks for the author by auth_email if it is 'IN' the $results array, but it is not finding the authors in the 2nd database as I expected. Please note the different connString
require_once('ConnString/SecondAuth.php');
mysql_select_db($xxxxx, $xxxxxx);
$query_Recordset2 = "SELECT auth_email FROM Authors WHERE auth_email IN('$results')";
$Recordset2 = mysql_query($query_Recordset2, $xxxxxx) or die(mysql_error());
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
The var_dump is 0 but I know that there are two records in there that should be found.
I've tried various combinations of IN like {$results}, but when I got to "'$results'", it was time to ask for help. I've checked all the available posts and none resolve my problem though I am now more familiar with the wild goose population.
I thought that since I swapped out the connection string, maybe $result was made null so I re-set it to the original connString and it still didn't find auth_email in $results in the same database where it certainly should have done.
Further, I've swapped out connStrings before with positive results, so... hmmm...
My goal, when working, is to echo the Recordset2 into a form with a do/while loop that will permit me to update their record in the 2nd db. Since the var_dump is 0, obviously this below isn't giving me a list of authors in the second table whose email addresses appear in the $results array, but I include it as example of what I want use to start the form in the page.
do {
$row_Recordset2['auth_email_addr '];
} while($row_Recordset2 = mysql_fetch_assoc($Recordset2));
As always, any pointer you can give are appreciated and correct answers are Accepted.
If you have a db user that has access to both databases and tables, just use a cross database query to do the update
UPDATE
mydb.Authors,
mydb2.Authors
SET
mydb.Authors.somefield = 'somevalue'
WHERE
mydb.Authors.auth_email = mydb2.Authors.auth_email AND
mydb2.Authors.Cancel= 'Cancel'
The IN clause excepts variables formated like this IN(var1,var2,var3)
You should use function to create a string, containing variables from this array.
//the simplest way to go
$string = '';
foreach($results as $r){
foreach($r as $r){
$string .= $r.",";
}
}
$string = substr($string,0,-1); //remove the ',' from the end of string
Its not tested, and obviously not the best way to go, but to show you the idea of your problem and how to handle it is this code quite relevant.
Now use $string instead of $results in query

Check if username exists, if so, increment by one

When a username is inserted into my database, such as:
John_Smith
I need to check if there is already a John_Smith present. If so, increment it by 1 to become John_Smith_1
So if the following usernames already exist:
John_Smith
John_Smith_1
John_Smith_2
John_Smith_3
....up to John_Smith_10
I need the next John_Smith inserted to be incremented to John_Smith_11.
So far, I have searched and come up with this:
$preferredname= "John_Smith"
//check for duplicate user names
$duplicate= check_for_duplicate_username($preferredname);
//if duplicate, increment the preferredname
if ($duplicate)
{
$parts = explode("_",$preferredname);
if (isset($parts[1]))
$preferredname = $parts[0]."_".$parts[1]."_".($parts[2]+1);
else $preferredname = $parts[0]."_".$parts[1]."_1";
}
This, I believe would work for only the first matching usernames. My problem is checking the database for the version of the name with the highest number.. This is my sql:
function check_for_duplicate_username($name)
{
// check if username already exists
$sql = "SELECT * FROM users WHERE user_username=$name";
//then return duplicates
You can use this query:
$sql = 'SELECT * FROM users WHERE user_username LIKE ' . $name . '_%';
the above will query for rows in which user_username have value similar to John_Smith_* ( where * is any valid character including number, which you have to check later )
you can use this php statement for getting user's suffix number:
preg_match( '/([0-9]+)$/', 'John_smith_10', $matches );
$user_number = $matches[0];
While this may not be the best solution in the grand scheme of things, here is an answer that addresses what you were specifically trying to do. The following query returns the number of users with either $name or $name_123 SELECT COUNT(*) FROM users WHERE user_username REGEXP '$name[_0-9]*$'; So if the value is 0 you can simply use $name by itself, otherwise you can use $name."_". + the number returned by the query.
But as many people have mentioned, prly not the best idea to autoassign usernames (very web 1.0 :P ). I'd recommend email addresses. Another option is to use whatever userid the social app uses along with another field identifying the social app (if you have multiple), and then using an autoincremented id field as the unique primary key..
I had a similar problem I was trying to solve today and did it like this. In my case I needed to store/create a unique directory name based on the users first initial/last name:
$username = "bjones";
$usersql = "SELECT * FROM users WHERE username LIKE '$username%'";
$usercnt = mysqli_num_rows(mysqli_query($con,$usersql));
// If bjones, bjones1, bjones2, etc already exists
if ($usercnt >= 1) {
$num = ++$usercnt; // Increment $usercnt by 1
$username = $username . $num; // Add number to username
}
Assuming bjones, bjones1, bjones2 already exists, I would end up with bjones3.

How to loop my function based on query result

I wrote a function which makes a random id makeid(); Just to ensure the id is unique I have a SQL statement which checks if the id already exists.
$does_id_exist = mysql_query("SELECT COUNT(*) AS count FROM signups WHERE affid='$affid'");
if(mysql_num_rows($does_id_exist) == 1)
{
#loop function and perform query again
}
else
{
#insert record
}
So I'm having trouble with looping the function. How do I loop my function makeid() and perform the $does_id_exist check to ensure that each ID is unique.
--UPDATE-- Just to clarify- My code makes an id like YES#281E But before I INSERT this id into the users record. I just need to verify IF any other user already has this id. IF another user has this id that event must trigger my function to create a new id e.g. WOW!29E3 and again check the sql/query to ensure no other user has that id. Continue to loop if fails or end and INSERT if the id is available.
You can either just use a primary key on your database table, or something like this:
<?php
// the id to insert
$newId = null;
// populate with results from a SELECT `aff_id` FROM `table`
$currentIds = array();
// prepopulate
for( $i=0; $i<100000; $i++ )
{
$currentIds[] = "STRING_" + rand();
}
// generate at least one id
do
{
$newId = "STRING_" + rand();
}
// while the id is taken (cached in $currentIds)
while( in_array($newId, $currentIds) );
// when we get here, we have an id that's not taken.
echo $newId;
?>
Output:
STRING_905649971 (run time 95ms);
I'd definitely not recommend running the query repeatedly. Perhaps a final check before you insert, if your traffic volume is high enough.
Do not do COUNT(*), because you do not need to know how many rows is there (it should be 0 or 1 as you need Id unique), so even DB finds your row it will still be checking for the whole table to count. You really care if you got 1 row, so just select for row with that ID and this sufficient. You should also avoid using rand() - this does not help as you see and you cannot predict how many loops you can do before you find "free slot". use something predictable, like date prefix, or prefix incremented each day. anything that would help you narrow the data set. But for now (pseudocode!):
$id = null;
while( $id == null ) {
$newId = 'prefix' . rand();
mysql_query("SELECT `affid` FROM `signups` WHERE `affid`='${newId}'");
if( mysql_num_rows() == 0) {
$id = newId;
break;
}
}
Ensure you got DB indexed, to speed things up.
EDIT: I do agree that any cache would be useful to speed things up (you can add it easily yourself based on #Josh example), still, I think this is fixing at wrong place. If possible rethink the way you generate your ID. It does not really need to be auto increment, but something more predictable than rand() would help you. If your ID does not need to be easily memorable and it is not any security concern to have them sequential, maybe use numbers with other base than 10 (i.e. using 26 would use all digits + letters so you'd end with PREFIX-AX3TK, so string as you want, and at the same time you would easily be able to quickly generate next Id

if name exists save as name(1) name(2) and so on

There's a mysql database that stores ids and names, when users are creating names with a form they can create existent names since unique ids are the ids such as:
d49f2c32f9107c87c7bb7b44f1c8f297 name
2fa9c810fbe082900975f827e8ed9408 name
what i want to do is saving the second "name" -> "name(1)" when inserting into database.
So far what I've got is this as the idea
lets say the name entered is 'name'
$input = 'name';
select the name we want to check from mysql database
mysql_query(SELECT * FROM `table` WHERE `name` = '$input');
if the result exists, then insert as $input.'(1)'
my question is what if name exists, and name(1) also exists, then how can i add the name(2) there...
You could return the number of people with that name in the database, then add 1 to that number.
SELECT COUNT(id) FROM table WHERE name LIKE '$input(%)');
$i = 1;
$sourceName = $name;
while( sql "SELECT COUNT(*) FROM table WHERE name = '$name'" ) {
$name = $sourceName.' ('.$i.')';
$i++;
}
At this point you have the final $name (with $i counting the iteration)
Something like this should do the trick:
SELECT * FROM table WHERE name = '$input' OR name LIKE '$input(%)'
Note that for this to work, you'd need to escape any percent signs in $input in the LIKE clause, otherwise they'll be treated as wildcards.
Use a regex that checks for integers between two parentheses at the end of the string. If there exists an integer, add 1 to it.
You could also attempt to do it the other way around, make name field unique and try to input it in a while loop, if it fails add ($i) and do $i++ every iteration.
//edit:
The problem with using solutions that do a like comparison is that you will get false positives, for instance $hi% will also count hippie. Which gives you unnecessary (1) additions!

Categories