如何修复“数组索引超出范围”?

时间:2018-10-15 19:49:50

标签: php sql

登录到Unity项目时,在C#代码的这一行出现错误“数组索引超出范围”

   if (www.text[0] == '0')

www.text从此php脚本中提取(调试时www.text返回null,因此我的脚本一定是错误的。)

<?php

$con = mysqli_connect('localhost', 'root', 'root', 'unityaccess');

//check that connection happened
if (mysqli_connect_errno())
{
    echo "1: Connection failed"; //error code #1 = connection failed
    exit();
}

$username = $_POST["name"];
$password = $_POST["password"];

//check if name exists
$namecheckquery = "SELECT username, salt, hash, score FROM players WHERE 
username = ' " . $username . "';";

$namecheck = mysqli_query($con, $namecheckquery) or die("2: Name check query 
failed"); //error code #2 - name check query failed
if (mysqli_num_rows($namecheck) != 1)
{
echo "5: Either no user with name, or more than one";
exit();
}

//get login info from query
$existinginfo = mysqli_fetch_assoc($namecheck)
$salt= $existinginfo["salt"];
$hash = $existinginfo["hash"];

$loginhash = crypt($password, $salt);
if($hash != $loginhash)
{
echo "6: Incorrect password"; //error code #6 - password does not hash to 
match table
exit();
}

echo "0\t" . $existinginfo["score"];

?>

我正在学习教程,并且是php和sql的新手。

https://www.youtube.com/watch?v=NVdjlXgbiMM

在教程中,他的代码与我的代码完全相同。我自己看一下,我会认为回显为“ 0 \ t”。 $ existinginfo [“ score”];问题是,放置选项卡并不能将其分成数组。在他的代码中,他运行了它,而且还好,所以我还必须缺少其他东西吗?

1 个答案:

答案 0 :(得分:2)

在此行的查询中,'后面有一个空格:

$namecheckquery = "SELECT username, salt, hash, score FROM players WHERE 
username = ' " . $username . "';";

因此,如果输入的用户名是user1,它将在数据库中查找<space>user1(其中<space>表示空格)。删除该空间。

$namecheckquery = "SELECT username, salt, hash, score FROM players WHERE 
username = '" . $username . "';";

实际上,如果您学会了使用准备好的语句,那就更好了,这样几乎不可能发生这样的问题,并使代码免于SQL注入。阅读How can I prevent SQL injection in PHP?