使用mysqli和php(PhpMyAdmin)检查用户名是否已存在

con.php

<?php
$_HOST="localhost";
$_USER="root";
$_PASS="";
$_DBNM="test";

$con=mysqli_connect($_HOST, $_USER, $_PASS, $_DBNM);

if ($con === false)
{
    die ("Database Connection Failed");
}
echo "Database Connection Succeed <br>";
?>

register.php

<?php
include("con.php");
$username=$_POST['username'];
$password=$_POST['password'];
$level=$_POST['level'];

$sql = "select username from user where username='$username'";
$data = mysqli_query($con,$sql);

if(mysqli_num_rows($data) > 0)
{   
    echo '<script language="JavaScript">alert("Username Already Exist!");
        document.location:"register.html"</script>';
}
else
{
    $query = $con->query("INSERT INTO user (username, password, level) 
        VALUES ('$username', '$password', '$level')");
    echo '<script language="JavaScript">alert("Registration Succeed!");
    document.location:"index.php"</script>';
}

?>

so the code is working for not inserting account if the username already exist, but it doesn't show the echo and it got stuck on the con.php. Also, When I enter the non-exist username, the account added successfully but the echo didn't apppear.

Instead of using javascript to do a redirect you can use the header in php.

see example code.

if(mysqli_num_rows($data) > 0){   
    header("location:register.html");
    exit();
}else{
    // do query...
   header("location:index.php");
   exit();
}

Also you should consider using prepare statements or moving to PDO
ref PDO: http://php.net/manual/en/pdo.prepare.php
ref header: http://php.net/manual/en/function.header.php