-1

I'm trying to learn really basic PHP/SQL and I did search prior to asking but they're really complicated examples for me.

So here is a basic tutorial code that I used and edited lightly.

What can I add to the existing code to check if the username already exists so I don't create it again?

<html>
<body>


<?php

        // put your code here
        $servername = "localhost";          //should be same for you
        $username = "user";                 //same here
        $password = "password";             //your localhost root password
        $db = "myDB";                     //your database name


        $conn = new mysqli($servername, $username, $password, $db);
        if($conn->connect_error){
            die("Connection failed".$conn->connect_error);
        }else{
            echo "Connected<br>";
        }




$sql="INSERT INTO login (username, password)
VALUES
('$_POST[username]','$_POST[password]')";

        echo "<br><br>Inserting  into db: ";
        if($conn->query($sql)==TRUE){       //try executing the query 
            echo "Query executed<br>";
        }
        else{
            echo "Query did not execute<br>";
        }

        $conn-> close();            //close the connection to database

?>
</body>
</html>
J. Wu
  • 15
  • 4

1 Answers1

0

You could always set the username column in MySQL to be unique. It will reject any duplicates from there.

Colin Inskeep
  • 261
  • 3
  • 6
  • 16