mysql_num_rows()返回零

时间:2014-05-14 10:49:15

标签: php mysql

<form action = "index.php" method = "post">
username : <input type = "text" name = "uname" /><br>
password : <input type = "text" name = "pass" /><br>
submit : <input type = "submit" name = "submit" value = "submit" />
</form>

<?php
if(isset($_SESSION['id'])){echo $_SESSION['id'];}
if(isset($_POST['submit'])){
if ($_POST['submit'] == 'submit'){

$uname = $_POST['uname'];
$pass = $_POST['pass'];
$db = "davidedwardcakes";
$connect = mysql_connect('localhost', 'root', 'wtfiwwu');
$db_connect = mysql_selectdb($db, $connect);
if(!$db_connect){echo 'no';}

$query = "SELECT * FROM `users` WHERE uname ='$uname' AND pass = '$pass'";
$result = mysql_query($query, $connect);
if(mysql_num_rows($result) > 0){//echo 'index failed'; var_dump($result);}
while($row = mysql_fetch_array($result)){echo $row['uname']
 . "<br>";

session_start();
echo '<a href = "test.php">peruse</a>';
$_SESSION['id'] = $row['id'];}}

else{echo 'lol'; var_dump($query);}}

每当我想登录时,我都会收到错误消息:     string'SELECT * FROM users WHERE uname ='brown'AND pass ='kenji''(length = 61)

意味着我的$ query存在问题。如果我从$ query中删除$ pass查询,它可以正常工作,但在包含它时不会。请有人帮忙。

2 个答案:

答案 0 :(得分:1)

您的查询没有任何问题,但您的错误报告存在问题。例如,以下行:

if(mysql_num_rows($result) > 0){//echo 'index failed'; var_dump($result);}

当SQL查询返回至少一行时,将转储$result变量。也许你打算使用:

if(mysql_num_rows($result) < 1) { echo 'index failed'; var_dump($result); }

此外,还有一些注意事项:

  1. 不要将密码存储为纯文本。 http://alias.io/2010/01/store-passwords-safely-with-php-and-mysql/
  2. 不要使用mysql_*个功能;他们被弃用了。查看PDOMySQLi
  3. 您的代码可以SQL injection开放。

答案 1 :(得分:0)

语法

出错
$result = mysql_select($query, $connect);

而不是上面的代码替换为此代码

$result = mysql_select_db($query, $connect);