Home > Software design >  Complex algorithm
Complex algorithm

Time:09-23

I've tried to rack my brain but got stucked.. but i believe this is possible, because there are gurus out there. There is this affiliation websites. If a user is the first to register on the app, he wont be under anyone but the next six users that registered would be under the first user,when it is more than six the seventh user wont be under anyone, any other six users that registered would be under the seventh users, and so on.. I created two tables, the users table and the table to keep track of users under users..

 if(isset($_POST['submit'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $pre = $db->prepare("SELECT * FROM affi");
     $pre->execute();
    $fetch = $pre->fetchAll();
    // print_r($fetch);die;
    if(count($fetch) < 1) {
        //checking if this is the first user 
        $create_user = $db->prepare("INSERT INTO users (name, email, password )
        VALUES('$name', '$email', '$password')");
        $stmt = $create_user->execute();
        if($stmt)  {
            $refer = $db->prepare("INSERT INTO refer_customer (email)
            VALUES('$email')");
            $stmt = $refer->execute();
            header("Location: Index.php");
        }
    } else if(count($fetch) <= 7) {
        //trying to attach other six users that would register under the first one
        $get_user = $db->prepare("SELECT FIRST(id) from users ");
         $get_user->execute();
         $result = $create_user->fetch(PDO::FETCH_OBJ);
        if($result) {
        $create_user = $db->prepare("INSERT INTO users (name, email, password )
        VALUES('$name', '$email', '$password')");
        $stmt = $create_user->execute();
        if($stmt)  {
            $refer = $db->prepare("INSERT INTO refer_customer (refere_id ,email)
            VALUES('$result->id','$email')");
            $stmt = $refer->execute();
            header("Location: Index.php");
        }
    }  
    
    }
}

Got stucked dont even know how this gonna end because there will be unlimited users if you know what i mean.. Please any help is appreciated

CodePudding user response:

This sounds like quite a simple problem.

  1. You could number your users when they register: user 1, 2, 3, etc. The best way to do this would be with an auto-increment index in your database. Let's call this column userId.

  2. Next is a little trick: You can use the modulo operator in PHP, like this: $position = $userId % 7; This will return a number between 0 and 6. $position == 0 is for the leader of the next 6 users.

And that's it. MySQL also has the modulo operator.

  • Related