MySQL& PHP,mysqli_num_rows总是返回0

时间:2016-07-20 10:11:43

标签: php mysql

我在写一个基本的寄存器脚本时遇到了一些问题,我似乎无法修复它。

嗯,这是代码:

$check_usr = mysqli_query($con,"SELECT FROM users WHERE user_name = $usr");

if (mysqli_num_rows($con,$check_usr)>=1)
    {
    echo "This Username already exists";
    }
    else
    {
    echo "This Username is available";
    }

问题是我无法进行验证(以便人们无法两次注册同名):

SELECT FROM users WHERE user_name = $usr

总是返回“此用户名可用”,即使我曾经用(nevondrax)测试它的用户在MySQL表中(这就是它的样子click

2 个答案:

答案 0 :(得分:1)

您的查询(mysqli_num_rows)没有选择任何行,因此没有返回任何行,因此SELECT FROM users WHERE user_name = dummy始终为零。

此外,您还错过了参数周围的一些引号。现在你的查询看起来像这样: SELECT * FROM users WHERE user_name = 'dummy'

正确/应该是: $check_usr = mysqli_query($con,"SELECT user_name FROM users WHERE user_name = '$usr'"); if($check_usr === false) { echo(mysqli_error($con)); } else { if (mysqli_num_rows($check_usr)>=1) { echo "This Username already exists"; } else { echo "This Username is available"; } }

如果我们采用您的代码块并进行调整,它可能如下所示:

$check_usr = mysqli_query($con,"SELECT FROM users WHERE user_name = $usr");

答案 1 :(得分:1)

您选择查询的语法错误。

$check_usr = mysqli_query($con,"SELECT fieldname FROM users WHERE user_name = $usr");

您必须将语法编写为

using (SqlConnection connection = new SqlConnection(connectionString))
{
    DataSet userDataset = new DataSet();
    SqlDataAdapter myDataAdapter = new SqlDataAdapter(
        "SELECT au_lname, au_fname FROM Authors WHERE au_id = @au_id", 
        connection);                
    myCommand.SelectCommand.Parameters.Add("@au_id", SqlDbType.VarChar, 11);
    myCommand.SelectCommand.Parameters["@au_id"].Value = SSN.Text;
    myDataAdapter.Fill(userDataset);
}

您错过了在SELECT

之后给出字段名称