PHP MySQL尝试访问类型为null的值的数组偏移量

I've userCheck.php on localhost with MySQL InnoDB database on phpMyAdmin, it is same already checked and used working code, maybe except collation utf8_general_mysql500_ci.

I can't figure out, what I've missed here, I've tried with empty and manually filled rows, but ajax request with user value to userCheck.php shows Trying to access array offset on value of type null on line 16 $ID = $row['ID']; in userCheck.php and echo condition Username available when .js received echo is <br /> instead "Username available" string:

注意:尝试访问数组中类型为null的值的偏移量   C:\ xampp \ htdocs \ user \ web \ dir \ php \ userCheck.php在线   16个用户名可用
<?php
  require 'connection.php';
  if( isset($_POST['username'])) 
  {
    $username = mysqli_real_escape_string($con, rtrim(ltrim($_POST["username"])));

    if($username == '') 
    {
       echo 'Please enter required information';    
    } else {
        $query = "SELECT ID FROM registration where username='".$username."' ";

        $result = mysqli_query($con, $query);
        $row = mysqli_fetch_assoc($result);

        $ID = $row['ID'];

        if($ID != null) 
        {
           echo "User already exist: ".$ID;
        } 
        else 
        {
           echo "Username available";       
        }
    }
  } 
  else 
  {
     echo 'Something is wrong!';
  }
?>
评论
  • 洋子舒
    洋子舒 回复

    If the query doesn't find any matching rows, mysqli_fetch_assoc() returns NULL, so $row['ID'] will fail.

    You should check $row rather than $row['ID']

    $row = mysqli_fetch_assoc($result);
    
    if($row) 
    {
        echo "User already exist: ".$row['ID'];
    } 
    else 
    {
        echo "Username available";       
    }