问题描述:

I have this piece of PHP code:

<?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();

?>

However, when I try to run this code I get these errors:

Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\wamp\www\PHP testing\login.php on line 9

and

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'users WHERE username='alex'' at line 1

Can someone explain to me what I'm I doing wrong here?

网友答案:

You must specify a table from which you're selecting with FROM keyword:

$query=mysql_query("SELECT * FROM users WHERE username='$username' ");
$numrows=mysql_num_rows($query);
网友答案:

you should really check for errors after your query, then the system will tell you what is wrong

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

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

$numrows = mysql_num_rows($query);

as @mike commented, your select query is missing the from bit

"SELECT * FROM users WHERE username='$username' "
网友答案:

Well Your code is vulnerable to SQL Injection Attack

$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']);
网友答案:
$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);

and it will evaluate resource

网友答案:
$query = mysql_query("SELECT * users WHERE username='$username' ");
if (mysql_error() {
   die(mysql_error());
}
$numberOfRows = mysql_num_rows($query);
echo $numberOfRows;
相关阅读:
Top