0

I am trying to make a PHP function check against a MySQL DB if a value that has been randomly created previously exists, if it does then for it to repeat until it makes a value in which does not exist.

Currently i have failed miserably, although in precedence i believed my method would have worked, it just does not.

The PHP

I tried this in the script on its own and then realised that php functions do not run unless they are called.

 conn(); //db connection 
    function genID() {
        $newIDref = uuaig(10);
        $queryCHECK = "SELECT *
                        FROM contentArticle_vids
                         WHERE videoArticle_id = '$newIDref'
                    ";
            $resultCHECK = mysql_query($queryCHECK);
            $numrows = mysql_num_rows($resultCHECK);

        if ($numrows !== 0) {
            genID();
            die();
        }
    }

So.. i then tried this, of which then made it really unhappy (broke the whole page).

conn(); //db connection 
genID();

function genID() {
    $newIDref = uuaig(10);
    $queryCHECK = "SELECT *
                    FROM contentArticle_vids
                     WHERE videoArticle_id = '$newIDref'
                ";
        $resultCHECK = mysql_query($queryCHECK);
        $numrows = mysql_num_rows($resultCHECK);

    if ($numrows !== 0) {
        genID();
        die();
    }
        if ($numrows === 0) {
        return $newIDref;
        die();
    }
}

For reference the random string generator is the uuaig(10).

I ultimately need the random string generated and then returned if the string is confirmed as non existent in the database.

How do i proceed?

6
  • Where are you actually connecting to your database? Commented Jun 19, 2014 at 22:24
  • above this in a function of which is confirmed working. @MichaelO'Brien Commented Jun 19, 2014 at 22:25
  • 1
    why is die() there? for debugging or is the actual code? if you want to recursively call your function, you must end it with return genID(); please notice that your code is missing return, after that, both die() are unnecesary Commented Jun 19, 2014 at 22:37
  • letme know what is uuaig(), is your custom random string function? Commented Jun 19, 2014 at 22:47
  • uuaig() is te random string gen yes. Commented Jun 19, 2014 at 22:52

2 Answers 2

2

Why make a select at all? Simply put a unique index on videoArticle_id. Then when you try to generate and insert a new id, just handle the insert failure and retry with a new id.

If you have a code scheme for generating the id's and expect few id collisions, this will be way more efficient.

So your function might look like:

function genID() {
    $idSuccess = false;
    $max_retries = 3;
    $i = 1;
    while (false === $idSuccess && $i <= $max_retries) {
        $newIDref = uuaig(10);
        $queryCHECK = "INSERT INTO contentArticle_vids (`videoArticle_id`)
            VALUES ('$newIDref')";
        $idSuccess = mysql_query($queryCHECK);
        $i++;
    }
    if(false === $idSuccess) {
        error_log('Could not generate ID in genID()');
        return false;
    }
    return $newIDref;
}

Note I have added a max retry limit so you don't have infinite loop possibility. Also, note that this will go ahead and reserve the spot for this new unique ID in the DB table.

Finally, it is basically obligatory that I note your are using the deprecated mysql extension. You really should not be writing new code using this extension.

Sign up to request clarification or add additional context in comments.

4 Comments

that is what im trying to achieve, but i wish to cycle in a loop for the id creation and check. I know the chances of it being the same id is slim but i still wish to make it varify the string is ok
@MikeBrant Might I suggest a do {...} while() instead? Would be a bit cleaner and better to read (imo). Also, of yoda conditions I am a fan not, but that is totally up to you
I managed to accomplish my desired result. Ill admin i do like your answer, but it just did not accomplish what was necessary in this case scenario. As for mysql query yes i know, i am changing to mysqli on this project.
@kingzero Yeah do..while is just as valid here and would at least save you from declaring $idSuccess before the loop. I am a big fan of yoda conditions as if you make a stupid typo like (false = $var) you get a fatal error` whereas ($var = false) gives you a not always as easy to spot debugging problem.
0

After some tinkering i managed to figure out the correct way to achieve my desired result.

//genID();


function genID($newIDref) {
    $status = false;
    $i=0;
    while ($status === false) {
        $newIDref = uuaig(10);
        $queryCHECK = "SELECT *
                        FROM contentArticle_vids
                         WHERE videoArticle_id = '$newIDref'
                    ";
            $resultCHECK = mysql_query($queryCHECK);
            $numrows = mysql_num_rows($resultCHECK);

        if ($numrows === 0) {
            $status = true;
            return $newIDref;
        }

        $i++;

        // testing
        /*
            if ($i > 5) {
                echo 'fin';
                die();
            }
        */  
        // testing
    }
}

$newIDref = genID($newIDref);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.