-2

I have an issue with my code to check if a username is already registered. I did a search on here to look at the different solutions and implemented some of them on my code but I still can't seem to get it to work. I tried registering the same username multiple times it still lets register without alerting me that the username is already taken. I apologize if this is easy to solve as I am new to php and mysql.

I tried multiple solutions but none seem to work for me. This is my latest iteration of my code.

<?php
session_start();

if (isset($_POST['submit'])) {

    $dbCon = mysqli_connect("localhost", "root", "badassrichv", "FootballDB");

    if (mysqli_connect_errno()) {
    echo "Failed to connect: " . mysqli_connect_error();
    }

    $username = strip_tags($_POST['name']);
    $password = strip_tags($_POST['password']);
    $email = strip_tags($_POST['email']);

$checkName = 'SELECT * FROM user WHERE username = "$username"';
$run = mysqli_query($dbCon, $checkName);
$data = mysqli_fetch_array($run, MYSQLI_NUM);

if ($data[0] > 0) {
    echo "<script>alert('Name already registered. Input a different name')</script>";
    exit();

} else {

$sql = "INSERT INTO user (username, password, email) VALUES ('$username', '$password', '$email')";

}

....More code
  • Firstly, you should never put POST data directly into a query. You're just asking for mayhem. Google mysqli parameters. Second, try this to inspect the data you're getting back from the db: `echo '
    '.print_r($data, true).'
    ';`
    – larsAnders Apr 24 '16 at 22:56

2 Answers2

0

Try to put a unique key on the username column in your database, and capture the duplicate entry error code

-1

Replace if ($data[0] > 0) { with if (mysqli_num_rows($run) > 0) {.

After doing that you can also get rid of the $data = mysqli_fetch_array($run, MYSQLI_NUM); line.

Chris
  • 5,571
  • 2
  • 20
  • 32