Page 1 of 1

Please help me implement this loop properly ->

Posted: Thu Oct 09, 2008 8:29 am
by aditya2071990
Here is the algorithm for my loop:

1. Generate a Random Number

2. Check in the mysql database if the Random number was previously generated

3. If it was generated previously, go back to step 1.

4. If it is not found in the database, it was not generated before, so proceed and use the generated number.

And here is the code I used to achieve it:

Code: Select all

 
function generateRandom($input){
        
        $random_number = intval( "0" . rand(1,9) . rand(0,9) . rand(0,9) . rand(0,9) . rand(0,9) ); // random(ish) 5 digit int
    
        $random_string = chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)); // random(ish) 5 character string
        
        $randomSum = $random_number.$random_string.'adjafhdklf';
        
        $mostRandom = md5($randomSum.$input);
        
        return $mostRandom;
    
    };
 
//generate a random number
 
function generate_a_random(){
 
    $a_random_string = generateRandom(generateRandom(generateRandom(generateRandom(2071990))));
    
    return $a_random_string;
 
};
 
generate_a_random();
 
 
//check in DB
 
$checkForTwins = @mysql_query("select * from ad_details where unique_ad_id like '$a_random_string';");
 
if(!$checkForTwins){
 
echo 'checkForTwins failed';
 
echo mysql_error();
 
};
 
$result_of_twincheck = mysql_fetch_array($checkForTwins);
 
//check for twins
 
function check_for_twins(){
    
    if($result_of_twincheck['unique_ad_id'] == $a_random_string){
    
    generate_a_random();
    check_for_twins();
    
    }else{
        $unique_ad_id = $a_random_string;   
    };
};
 
check_for_twins();
 
function insert_data(){
 
};
 
 
I will write the insert_data() later...

It seems there is a mistake in my code. I am getting an error that says 'Connection to the server was reset' when I test it in my local server in IE, and Firefox says that the server is too busy. Can someone please correct my code? I know there is a small mistake, but I just can't find it :banghead:

Thanks is advance for everyone who helps...

Re: Please help me implement this loop properly ->

Posted: Thu Oct 09, 2008 8:39 am
by aceconcepts
Remove the first semi-colon ";" from your query.

Also use mysl_error() and remove "@" at beginning.

Re: Please help me implement this loop properly ->

Posted: Thu Oct 09, 2008 8:47 am
by VladSun
Bad code :)
1. Why do you do your SQL check with LIKE ? Use =
2. Why do you put your SQL queries outside of the function check_for_twins()?
3. You need a global modifier to get access to $result_of_twincheck in function check_for_twins()
4. You don't need rucursion.
5. Even if you had to use recursion, I wouldn't work this way.

In fact the whole bunch of code should be in 3 functions - generate_random_id(), db_check(), insert()

Re: Please help me implement this loop properly ->

Posted: Thu Oct 09, 2008 9:26 am
by onion2k
VladSun wrote:Bad code :)

3. You need a global modifier to get access to $result_of_twincheck in function check_for_twins()
It'll continue to be bad code if you use global. :)

Re: Please help me implement this loop properly ->

Posted: Thu Oct 09, 2008 9:45 am
by VladSun
onion2k wrote:
VladSun wrote:Bad code :)

3. You need a global modifier to get access to $result_of_twincheck in function check_for_twins()
It'll continue to be bad code if you use global. :)
Yep, it was noticed only for educational purposes ;)

Re: Please help me implement this loop properly ->

Posted: Thu Oct 09, 2008 11:16 am
by aditya2071990
Thanks for all the prompt replies!

And thanks also for taking time to point out all the other errors that make my code bad, I will definitely rectify them following your advice, but for now, the biggest doubt I have, I am listing below:

So you guys mean that even if I don't use recursion, and simply point to the generate_a_random() function as soon as my "if" statement finds out that a twin exists, like this:

Code: Select all

function check_for_twins(){
    
    if($result_of_twincheck['unique_ad_id'] == $a_random_string){
    
    generate_a_random();
    //note that I removed the pointer to check_for_twins();
    
    }else{
        $unique_ad_id = $a_random_string;   
    };
};
then it will automatically execute check_for_twins() function, following the order in which the code must be executed?

Someone once told me that php loads the entire code into memory before executing it, so I am li'l bit confused..

Re: Please help me implement this loop properly ->

Posted: Thu Oct 09, 2008 3:30 pm
by VladSun
1. You don't need an IF - you need a DO-WHILE ;) Because you can't be sure that the second attempt will be always successful.
2. Put all of your code regarding generating a random string in one function, then put all of your code checking in the DB and regenerating the random value in a second function (you should use the first function in the second). Don't use recursion.

Re: Please help me implement this loop properly ->

Posted: Fri Oct 10, 2008 11:43 am
by aditya2071990
Thank you :D I will try it out

Re: Please help me implement this loop properly ->

Posted: Sat Oct 11, 2008 3:00 am
by aditya2071990
Hello everyone, I hope I am not frustrating all of you, but please look into the code below that I made following your advice to use do...while, it still ain't working. Optimization is not a concern for me currently, it should just work...

Code: Select all

mysql_connect('localhost', 'root');
 
mysql_query('use wish4ababy');
 
function generateRandom1($input){
            
            $random_number = intval( "0" . rand(1,9) . rand(0,9) . rand(0,9) . rand(0,9) . rand(0,9) ); // random(ish) 5 digit int
        
            $random_string = chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)); // random(ish) 5 character string
            
            $randomSum = $random_number.$random_string.'adjafhdklf';
            
            $mostRandom = md5($randomSum.$input);
            
            return $mostRandom;
        
        };
 
function generateRandom2(){
    
        $finalRandom = generateRandom1(generateRandom1(generateRandom1(generateRandom1(2071990))));
        
        return $finalRandom;
    
    };
 
//check in DB
 
global $checkForTwins;
 
global $finalRandom;
 
$checkForTwins = @mysql_query("select * from ad_details where unique_ad_id='$finalRandom';");
 
    if(!$checkForTwins){
    
    echo 'checkForTwins could not be executed due to a database error';
    
    echo mysql_error();
    
    };
 
$result_of_twincheck = mysql_fetch_array($checkForTwins);
 
//check for twins
 
if($result_of_twincheck['unique_ad_id'] == $finalRandom){
 
$is_there_a_twin = 'y';
 
}else{
 
    $is_there_a_twin = 'n';
    
};
 
do{
 
    generateRandom2();
 
}while ($is_there_a_twin == 'y');
 
function insert_data(){
 
};

Re: Please help me implement this loop properly ->

Posted: Sat Oct 11, 2008 6:26 am
by aditya2071990
YAY! I found a solution that does not require me to check for twins in the database at all, I was reading up on some of the posts here, and I found one in which there is one solid piece of advice, so here is my new code for generating an absolutely unique random number:

Code: Select all

function getUserIP(){
    
    $userIPActual = $_SERVER['REMOTE_ADDR'];
    global $userIP;
    $userIP = str_replace('.','',$userIPActual);
    return  $userIP;
    
};
 
function getTime(){
    
    $microTimeActual = microtime(true);
    global $microTime;
    $microTime = str_replace('.','',$microTimeActual);
    return  $microTime;
    
};
 
function generateaRandom(){
    
    function generateRandom($input){
            
            $random_number = intval( "0" . rand(1,9) . rand(0,9) . rand(0,9) . rand(0,9) . rand(0,9) ); // random(ish) 5 digit int
        
            $random_string = chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)); // random(ish) 5 character string
            
            $randomSum = $random_number.$random_string.'adjafhdklf';
            
            $mostRandom = md5($randomSum.$input);
            
            return $mostRandom;
        
        };
    
    function generate_a_random(){
    
        $a_random_string = generateRandom(generateRandom(generateRandom(generateRandom(2071990))));
        
        return $a_random_string;
    
    };
    
    global $final_random;
    $final_random = generate_a_random();
    
    return $final_random;
    
};
 
getUserIP(); getTime(); generateaRandom();
 
$unique_id = $userIP.$microTime.$final_random;
Simply put, it gathers userIP, the time in microseconds at the moment of posting, and a random number. This will NEVER be repeated, right?

Thanks guys for all the help.

Re: Please help me implement this loop properly ->

Posted: Sat Oct 11, 2008 7:09 am
by mukunthan
<?php
$finalRandom = generateRandom2();
checkRandomsUniqueness($finalRandom);

// ======= FUNCTIONS ==========
function generateRandom1($input){

$random_number = intval( "0" . rand(1,9) . rand(0,9) . rand(0,9) . rand(0,9) . rand(0,9) ); // random(ish) 5 digit int

$random_string = chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)); // random(ish) 5 character string

$randomSum = $random_number.$random_string.'adjafhdklf';

$mostRandom = md5($randomSum.$input);

return $mostRandom;

};

function generateRandom2(){

$finalRandom = generateRandom1(generateRandom1(generateRandom1(generateRandom1(2071990))));

return $finalRandom;

};


function checkRandomsUniqueness ($rand_no){
$con = mysql_connect('localhost', $user,$password); if(!con) echo "Error:".mysql_error(); // replace $user & $password with orginal data
$dbcon = mysql_select_db ($dbname,$con); if(!dbcon) echo "Error:".mysql_error(); // replace $dbcon with orginal databasename

$result = mysql_query("select * from ad_details where unique_ad_id='$rand_no'");

if(mysql_num_rows($result) > 0){ // means random no. is already in the database

$finalRandom = generateRandom2();
checkRandomsUniqueness($finalRandom);

}else{ // means random no is unique and so insert the id by calling the insert _data function
insert_data();
}

}

function insert_data(){
// blah blah blah...
}
?>
Oh so u found an alternate soln. ok if u want to know the soln for your previous one. Try this

Re: Please help me implement this loop properly ->

Posted: Sat Oct 11, 2008 11:14 am
by aditya2071990
Thank you, mukunthan, it never hurts to know the answer for a problem :)

But I cannot make out the difference between the way you used recursion and I did...