mysql_num_rows()根本不工作

时间:2011-06-04 07:53:14

标签: php mysql

我有这段PHP代码:

<?php
$username=$_POST['username'];
$password=$_POST['password'];

if($username&&$password){
$connect=mysql_connect("localhost","root","") or die(" Couldnt connect");
mysql_select_db("phplogin") or die ("Can't find database" .mysql_error());  
$query=mysql_query("SELECT * users WHERE username='$username' ");
$numrows=mysql_num_rows($query);
if (!$query) {
die('Invalid query: ' . mysql_error());
}
}
else
die ("Enter username and password!") .mysql_error();
?>

但是,当我尝试运行此代码时,我收到了以下错误:

  

警告:mysql_num_rows()要求参数1为资源,布尔值在第9行的C:\ wamp \ www \ PHP testing \ login.php中给出

  

您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以便在第1行的'users WHERE username ='alex''附近使用正确的语法

有人可以向我解释我在这里做错了吗?

5 个答案:

答案 0 :(得分:5)

您必须使用FROM关键字指定要从中选择的表:

$query=mysql_query("SELECT * FROM users WHERE username='$username' ");
$numrows=mysql_num_rows($query);

答案 1 :(得分:5)

你应该在查询后检查错误,然后系统会告诉你出了什么问题

$query = mysql_query("SELECT * users WHERE username='$username' ");

if (mysql_error() {
   die(mysql_error());
}

$numrows = mysql_num_rows($query);

如@mike所述,您的选择查询缺少位

"SELECT * FROM users WHERE username='$username' "

答案 2 :(得分:4)

您的代码很容易受SQL Injection攻击

攻击
$username=$_POST['username'];
$password=$_POST['password'];

instead of above use this code 

$username= mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);

答案 3 :(得分:1)

$connect = mysql_connect("localhost","root","") or die("Couldn't connect!");
mysql_select_db("phplogin") or die("Couldn't find db");
$result = mysql_query("SELECT * FROM admin", $connect);
$numrows = mysql_num_rows($result);

它将评估资源

答案 4 :(得分:0)

$query = mysql_query("SELECT * users WHERE username='$username' ");
if (mysql_error() {
   die(mysql_error());
}
$numberOfRows = mysql_num_rows($query);
echo $numberOfRows;