Adding Suffix to Variable in a Loop

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
millsy007
Forum Commoner
Posts: 78
Joined: Wed Jul 02, 2008 7:00 pm

Adding Suffix to Variable in a Loop

Post by millsy007 »

I am writing a piece of code to insert names, part of the program needs to check for a duplicate name, upon there being a duplicate name I want to add a numerical suffix, and then increment this each time another duplicate is found/ or if a duplicate value has already been assigned.

So far I have:

Code: Select all

$suffix = '0';
while ($check!= 'no duplicates')
{
 
    $suffix ++;
    
    $query = "
    SELECT  passenger_name
    FROM    passengers, journey
    WHERE   journey.shuttle_id = '$id'
    AND     journey.id = passengers.journey_id
    AND     passengers.passenger_name = '$name'
    ";
    $qry_result = mysql_query($query) or die(mysql_error());
    $num_rows = mysql_num_rows($qry_result);
    if ($num_rows > 0) {
    
    while($row = mysql_fetch_array($qry_result)){
    $name = $row[passenger_name];}
    
    $name .= "$suffix";
    }
    
    else {
    $check = 'no duplicates';
    }
}
It works, but is setting the names as bob|bob1|bob12|bob123|bob1234|bob12345|bob123456|bob1234567 as opposed to just adding the one number suffix, how could I remedy this?
User avatar
papa
Forum Regular
Posts: 958
Joined: Wed Aug 27, 2008 3:36 am
Location: Sweden/Sthlm

Re: Adding Suffix to Variable in a Loop

Post by papa »

$suffix = 0;

I'd also change:

$name .= $suffix;
millsy007
Forum Commoner
Posts: 78
Joined: Wed Jul 02, 2008 7:00 pm

Re: Adding Suffix to Variable in a Loop

Post by millsy007 »

Thanks, but I changed both of these and still get bob1, bob12, bob123 etc?
User avatar
papa
Forum Regular
Posts: 958
Joined: Wed Aug 27, 2008 3:36 am
Location: Sweden/Sthlm

Re: Adding Suffix to Variable in a Loop

Post by papa »

How about instead of:

$name .= "$suffix";

Code: Select all

$matches[] = $name.$suffix;

Then at the bottom print_r($matches);
Post Reply