Php其他声明效果不佳

时间:2014-05-28 04:01:11

标签: php mysql

嘿伙计们我是php开发的新手,并且在php中遇到了一个项目..

我的HTML代码

<html>
<body>
<form name="input" action="database.php" method="post">
Username: <input type="text" name="user">
<br>
<input type="submit" value="Submit">
</form>

php code

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$name = $_POST['user'];

$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )

{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT username, phoneno FROM test';

mysql_select_db('test');

$retval = mysql_query( $sql, $conn );

if(! $retval )

{



 die('Could not get data: ' . mysql_error());

}


while($row = mysql_fetch_assoc($retval,MYSQL_ASSOC))

{

if($name != $row['username']) {

        echo "this username is not in our db";

} else {
echo "you are logged in";

}
}

mysql_close($conn);

?>

此处允许用户通过提供用户名进行登录,如果用户名不在数据库中,则必须收到消息this is not in out db。但是当我输入不存在于我们的数据库中的用户名时,它会给我留言3次像this username is not in our db you are logged in this username is not in our db ..这里的其他部分代码和实际代码一起工作..为什么会这样..希望你们能帮助我,

2 个答案:

答案 0 :(得分:0)

您循环遍历表中的所有行,因此在每次迭代时,if-else语句之一正在执行。

为了克服这个问题,你可以这样做:

$users = array();
while($row = mysql_fetch_assoc($retval,MYSQL_ASSOC))    
{
   $users[] = $row['username']; // store all usernames in an array
}

// now check for your condition
// in_array checks for existence of a string inside an array ($users)
if(in_array($name, $users)) {
   echo "You are logged in";
} else {
   echo "This username is not in our db";
}

答案 1 :(得分:-1)

解决问题的步骤:

1)我们正在检查数据库中是否有username = $_POST['user']

的条目

2)如果我们找不到条目echo "this username is not in our db"echo "you are logged in"

我的HTML代码

<html>
<body>
<form name="input" action="database.php" method="post">
Username: <input type="text" name="user">
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>

PHP代码

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'test';
$name = $_POST['user'];

$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

if(!$conn){ die('Could not connect: ' . mysqli_connect_error()); }

$retval = mysqli_query($conn, "SELECT username, phoneno FROM test WHERE username='".$name."'");

if(mysqli_num_rows($retval)<1){

    echo "this username is not in our db";

} else {

    echo "you are logged in";

}

mysqli_close($conn);
?>

你的错误:

1)你正在循环整个桌子&amp;因此它同时产生了3个输出