获取mysql_numrows():提供的参数不是有效的MySQL结果资源

时间:2013-12-27 01:09:26

标签: php mysql sql

我正在尝试创建一个简单的过程,检查在登录过程中是否已经使用了用户名。

我有一个简单的PHP脚本来查询数据库然后我检查是否有任何结果并回应用户

我得到的完整错误是: mysql_num_rows():提供的参数不是第9行/home1/tbronson/public_html/sandbox/uname_check.php中的有效MySQL结果资源

整个php脚本是:

<?php 
$user = "(removed for security)";
$pass = "(removed for security)";
$db = "budgetbidders_users";
$con = mysqli_connect($host,$user,$pass,$db);

$uname = strip_tags( trim( $_POST['uname'] ) );
$result = mysqli_query($con,"SELECT * FROM  `users` WHERE uname =  '" .$uname . '");
$numrows = mysql_num_rows($result); //line 9

if ($numrows > 0) {
    $end_result = "Username already taken";
    }
else {
    $end_result = "";
    }
echo $end_result;   



?>  

我已经搜索了几个小时并尝试了多种变体,这似乎是我能找到的最接近正确的,谢谢你的帮助!

3 个答案:

答案 0 :(得分:1)

您的代码中存在一些错误。

以下行在$uname的单引号之前缺少双引号:

$result = mysqli_query($con,"SELECT * FROM  `users` 
WHERE uname =  '" .$uname . '");
                           ^

然而,最好使用准备好的语句或PDO,或者你可以使用:

WHERE uname =  '$uname' // instead

另外,您已将已弃用的mysql_*函数与mysqli_*函数混合使用。

mysqli_querymysqli_num_rows()其中mysql_num_rows()需要更改为mysqli_num_rows

我还建议你改变:

$uname = strip_tags( trim( $_POST['uname'] ) );

为:

$uname = mysqli_real_escape_string($con, $_POST['uname']);

WHERE uname =  '" .$uname . "'

到:

WHERE uname =  '$uname'

您可以进行任何修改,两者都可以。 Do read this article on SO关于如何防止SQL注入。

立即尝试:

<?php 
$user = "(removed for security)";
$pass = "(removed for security)";
$db = "budgetbidders_users";
$con = mysqli_connect($host,$user,$pass,$db);

// the line below is better to use
$uname = mysqli_real_escape_string($con, $_POST['uname']);

// this is your original line of code which will work also
// $uname = strip_tags( trim( $_POST['uname'] ) );
$result = mysqli_query($con,"SELECT * FROM  `users` WHERE uname =  '" .$uname . "' ");
$numrows = mysqli_num_rows($result); //line 9

if ($numrows > 0) {
        $end_result = "Username already taken";
} else {
    $end_result = "";
}
echo $end_result;   

?>

答案 1 :(得分:0)

那是因为你使用的是mysql而不是mysqli

试试这个

$numrows = mysqli_num_rows($result):

答案 2 :(得分:0)

您不能混用mysql_*mysqli_*语法。

在您的情况下,您需要:

$numrows = mysqli_num_rows($result);

你之前的行上有一个语法错误(缺少引号)。