简体   繁体   中英

Why won't this PHP MySQL query work?

I have this as my PHP code:

$username=($_POST['username']);
$password=($_POST['password']);
$query="SELECT * from 'User' WHERE 'Username'='$username'";
mysql_query($query);

if($rows==0)
{
echo"<p> No rows found</p>";
}

else
{

while($row=mysql_fetch_array($query))
{
echo"rows found";
}

}
mysql_close($conn);

And my form code looks like:

<form name="login" action="mydamhlogin.php" method="POST">
<p>Username:<input type="text" name="username"></p>
<p>Password<input type="password" name="password"></p>
<p><input type="submit" value="Login"></p>
</form>

My Database column is called Username and I'm trying to select the rows that match the $username taken from the form but it always returns no rows, but the rows are definitely in the Database.

You are using wrong escape character as single qoutes use backtick operator instead like this

$query="SELECT * from `User` WHERE `Username`='$username'";
$result = mysql_query($query);

Also $rows is empty here you need to do this

$rows = mysql_num_rows($result);

then use this $rows variable to check the value of it.

use this

    $query="SELECT * from `User` WHERE `Username`='$username'";

you shouldnt use single quotes around table and columns , but backticks

also add this

 $rows = mysql_num_rows(mysql_query($query));

before this line

     if($rows==0)

edit:

change this

   while($row=mysql_fetch_array(mysql_query($query)))
   {
   echo $row['username'];   // this if you want output username , if you want something else just write column name
   }

EDIT2.

this is your code

   $username=($_POST['username']);
   $password=($_POST['password']);
   $query=mysql_query("SELECT * from `User` WHERE `Username`='$username'");
   $rows = mysql_num_rows($query);
  if($rows==0)
  {
  echo"<p> No rows found</p>";
 }

 else
{

while($row=mysql_fetch_array($query))
{
echo $row['username'];
}

}
mysql_close($conn);

Here you have missed many issues as $rows is not have any value and $query string. I have modified it use that:

$username=($_POST['username']);
$password=($_POST['password']);
$query="SELECT * from `User` WHERE `Username`='".$username."'";
$exeQuery = mysql_query($query);
$rows = mysql_num_rows($exeQuery)
if($rows==0)
{
echo"<p> No rows found</p>";
} else {

while($row=mysql_fetch_array($exeQuery))
{
echo"rows found";
}

}
$query="SELECT * from User WHERE Username='$username'";
$result=mysql_query($query);

if($result===false) //instead of $rows
...

EDIT:

if( ($result) && (mysql_num_rows($result)>0) )//instead of $rows
...

用这个,

$query="SELECT * from User WHERE `Username`='".$username."'";

查询的语法是错误的尝试这个

$query="SELECT * from User WHERE `Username`='".$username."'";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM