Page 1 of 1

Adding Suffix to Variable in a Loop

Posted: Fri Feb 27, 2009 7:15 am
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?

Re: Adding Suffix to Variable in a Loop

Posted: Fri Feb 27, 2009 7:18 am
by papa
$suffix = 0;

I'd also change:

$name .= $suffix;

Re: Adding Suffix to Variable in a Loop

Posted: Fri Feb 27, 2009 8:12 am
by millsy007
Thanks, but I changed both of these and still get bob1, bob12, bob123 etc?

Re: Adding Suffix to Variable in a Loop

Posted: Fri Feb 27, 2009 8:35 am
by papa
How about instead of:

$name .= "$suffix";

Code: Select all

$matches[] = $name.$suffix;

Then at the bottom print_r($matches);