0

I'd like to make this work somehow. the first query I got is to alert registration that the username they've chosen is already taken. Then refreshes the page again and if they enter an available username, they can register the said account. I'm able to show the message that the username is taken. The ELSE statement won't execute and insert the input data even if the user enters an available username.

if(isset($_POST['register'])){
    global $con;
    $stmt1 = $con->prepare("SELECT * FROM users WHERE userID = ?");
    $stmt1->bind_param("s", $new_user_name);

    $admin = $_SESSION['userID'];
    $new_user_name = $_POST['username'];
    $new_user_acc = $_POST['account_no'];
    $new_user_fullname = $_POST['fullname'];
    $new_user_pass = $auto_pass;
    $new_user_status = $_POST['status'];
    $new_user_group = $_POST['group'];
    $startTime = date("Y-m-d H:i:s");
    $datetime =date('Y-m-d H:i:s',strtotime('+7 hour',strtotime($startTime)));
    $auto_pass = substr(str_shuffle(implode(array_merge(range('a','z'), range('A','Z'), range (0,9)))), 0,9);

    $stmt1->execute();
    $stmt1->store_result();

    if($stmt1->num_rows > 0) 
    {
        echo"<script>alert('Sorry, that username is already taken. Please choose a different username')</script>";
        echo "<script>window.open('users.php','_self')</script>";
    }
    else
    {
        global $con;
        $stmt2 = $con->prepare("INSERT users set userID = ?, account_no = ?, password = ?, full_name = ?, status = ?, group_id = ?, created_at = ?, created_by = ?");
        $stmt2->bind_param("ssssiiss", $new_user_name, $new_user_acc, $new_user_pass, $new_user_fullname, $new_user_status, $new_user_group, $datetime, $admin);
        $stmt2->execute();

        if($stmt2->execute()){
            //echoes successful registration
        }
        else{
            //echoes an alert message failed.
        }
    }
    $stmt1->close();
    $stmt2->close();

}

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Ron
  • 3
  • 2
  • You declare `$new_user_name` after you bind it to your `select` query, so what are you actually binding? – El_Vanja Apr 03 '20 at 07:05
  • Side note: never store passwords as plain text, use PHP's built-in [`password_hash`](https://www.php.net/manual/en/function.password-hash) and [`password_verify`](https://www.php.net/manual/en/function.password-verify) to store and check passwords. – El_Vanja Apr 03 '20 at 07:06
  • @El_Vanja they bind $new_user_name. this is how the binding works – Your Common Sense Apr 03 '20 at 07:30
  • I still can't get $stmt2 to insert data. Don't know what's wrong with my code above. – Ron Apr 03 '20 at 10:57

0 Answers0