我想用php和mysql验证用户名和密码。
我使用rowCount知道用户是否存在,但如果存在(rowCount> 0)我想从用户那里获取值。
public static function validateUser($user)
{
$dto = NULL;
$exist = false;
$strUsername = $user->getUsername();
$strPassword = $user->getPassword();
try
{
$pdo = new PDOClass();
$stmt = $pdo->prepare("select username, password, name, age, ocupation, id from user where username = ? AND password = ?");
$stmt->bindParam(1, $strUsername);
$stmt->bindParam(2, $strPassword);
$stmt->execute();
$resultado = $stmt->fetchAll();
if($stmt->rowCount()>0) {
exist true;
//get user values
$user->setName(??);
$user->setAge(??);
}
} catch (Exception $ex) {
echo"Error SQL ".$ex->getMessage();
}
return $exist;
}
答案 0 :(得分:0)
而不是:
$resultado = $stmt->fetchAll();
if($stmt->rowCount()>0) {
exist true;
//get user values
$user->setName(??);
$user->setAge(??);
}
你会这样做:
// Fetch only one row
$resultado = $stmt->fetch(\PDO::FETCH_ASSOC);
if($resultado !== false) {
// If the user exists you can get its name and age and perform any
// kind of validation you want
$user->setName($resultado['name']);
$user->setAge($resultado['age']);
}
答案 1 :(得分:0)
要从用户获取值,您必须使用带有文本字段和密码字段的HTML表单。一旦用户按下提交按钮,使用PHP $ _REQUEST []或$ _GET []或$ _POST []全局变量从这些字段中检索值。
<form method="" action="">
Username
<input type="text" name="user">
PasSword
<input type="password" name="pass">
<input type="submit">
</form>
Php代码
$user=$_REQUEST["user"];
$pass=$_REQUEST["pass"]