f2k
f2k

Reputation: 99

Control multiple print of message based on database results

After following some answers and articles finally i came up with the function that will generate key(number) automatically when it is not exist in the database and codes works, but the problem is when the code exist the notification that "CODE EXIST" form something like a loop and print multiple notifications. Base on my codes where do i get it wrong and how can I fix it?

    <?php
 //HERE IS THE FUNCTION  
      function MyFunction($xIsConnection){
    // CODE GENERATION
      //$Code=(rand(10,1000));
       $Code='001';
       $query= "SELECT * FROM parent WHERE code='$Code'";
        if($result= mysqli_query($xIsConnection,$query)){
      if(mysqli_num_rows($result)>0){
       echo " CODE EXIST<br>";

  // CALL FUNCTION TO GENERATE NEW CODE
         MyFunction($xIsConnection);
            }
       else{
       echo "NOT EXIST  <br>";
       echo $Code;
         }
        }
    else{
    echo"failed";
    }
    }
    require_once('dbConnect.php');
    MyFunction($con);
    mysqli_close($con);

    ?>

Upvotes: 1

Views: 47

Answers (1)

Mr. Laststringx
Mr. Laststringx

Reputation: 25

The answer is never ending recursion.

<?php
     //HERE IS THE FUNCTION  
          function MyFunction($xIsConnection){
        // CODE GENERATION
          //$Code=(rand(10,1000));
           $Code='001';
           $query= "SELECT * FROM parent WHERE code='$Code'";
            if($result= mysqli_query($xIsConnection,$query)){
          if(mysqli_num_rows($result)>0){
           echo " CODE EXIST<br>";

      // CALL FUNCTION TO GENERATE NEW CODE
             MyFunction($xIsConnection);         // this line is responsible for your error. Recursion
                }
           else{
           echo "NOT EXIST  <br>";
           echo $Code;
             }
            }
        else{
        echo"failed";
        }
        }
        require_once('dbConnect.php');
        MyFunction($con);
        mysqli_close($con);

        ?>

Upvotes: 1

Related Questions