hi:)
I want the script to check the db table to see if there is the same username as what the user has submit with the register form, then stop the script from registering, but if the user has submited a new username, then registering.
I think the script should chack db and store all usernames in Array, and then in the If part check the value of $username with all values of that Array but i don't know how to do that.
This is my script but it need to be edited:

    $username = $_POST['username'];

    $sql = ("SELECT Username FROM Users");
    $result = $conn->query($sql);

    foreach($result as $key => $row) {
        $array = array($row['Username']);
    }

    if($row['Username'] != $username) {
    include('connection.php');
    $sql = "INSERT INTO Users (Username, Password)
    VALUES ('$username', '$password')";

    $conn->exec($sql);
    }

Is this part correct?!

            $array = array($row['Username']);

How should i edit this part?

if($row['Username'] != $username) {

I think what you can do is $sql = ("SELECT count(*) FROM Users where Username = '$username'");. If the result return count > 0, means the username existed in database. This will be better practice as imagine if the Users table is populated with a few bils of data, it will be a waste of spaces and process time to get and process the data manually.

Then your question about the coding $array = array($row['Username']);, this is wrong as the $array will always replaced. In order to collect the result into array, you should do $array[] = $row['Username'];.
Then the comparism part we can use in_array() to check if the username existed.

Well, the solution i found and works well: (Will post it for other members may have this problem too)

    $username = $_POST['username'];

    $sql = ("SELECT ID FROM Users WHERE Username = '$username'");
    $result = $conn->query($sql);

    foreach($result as $row) {
        $row['ID'];
        }
    if($row['ID'] == null){

        $sql = "INSERT INTO Users (Username, Password)
        VALUES ('$username', '$password')";

        $conn->exec($sql);
    }

Anyway thank you for answer!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.