如何创建一个if语句来检查变量是否在mysql数据库中

时间:2015-11-10 21:43:27

标签: php mysql pdo

try {
    $conn = new PDO("mysql:host=" . $_GLOBALS['servername'] . ";dbname=". $_GLOBALS['dbname'], $_GLOBALS['username'], $_GLOBALS['password']);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "SELECT * FROM us WHERE username='$suser' and password='$shashpass'"; // SQL Query

   $conn->exec($sql);

这是我的一些代码,如果suser和shashpass是正确的,我该怎么做呢 执行一些代码,否则执行其他代码

这不起作用

    <?php 
try 
{ 
    $conn = new PDO("mysql:host=" . $_GLOBALS['servername'] . ";dbname=". $_GLOBALS['dbname'], $_GLOBALS['username'], $_GLOBALS['password']); 
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    $query = $con->prepare("SELECT * FROM us WHERE username=:user and password=:password"); $query->bindParam(':user',$suser); 
    $query->bindParam(':password',$shashpass); $query->execute(); $result = $query->fetch(PDO::FETCH_ASSOC); 
    if(!empty($result)){ } else { } } 
catch(PDOException $e) {
    echo $sql . $e->getMessage(); 
} 

4 个答案:

答案 0 :(得分:3)

验证密码时,您不会预先对密码进行哈希处理。而是SELECT来自该用户的密码哈希(如果存在),然后使用password_verify()根据网络表单发送的纯文本密码验证它是否正确。

$stmt = $conn->prepare("SELECT password FROM us WHERE username=?");
$stmt->execute([$suser]);

if ($user = $stmt->fetch(PDO::FETCH_ASSOC)) {
    if (password_verify($plain_text_password, $user['password'])) {
        // Successful login
    }
    else {
        // Valid user, but invalid password
    }
}
else {
    // User doesn't exist
}

如果您没有使用password_hash()password_verify(),那么您就是在做错了。

答案 1 :(得分:1)

您以错误的方式使用PDO,您需要在PDO中使用prepared statements以防止mysql注入,尝试使用以下代码:

 try {
    $conn = new PDO("mysql:host=" . $_GLOBALS['servername'] . ";dbname=". $_GLOBALS['dbname'], $_GLOBALS['username'], $_GLOBALS['password']);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $query = $con->prepare("SELECT * FROM us WHERE username=:user and password=:password");
    $query->bindParam(':user',$suser);
    $query->bindParam(':password',$shashpass);
    $query->execute();
    $result = $query->fetch(PDO::FETCH_ASSOC);
    if(!empty($result)){
     // user is in database
    } else {

    // user is not there 
    }

答案 2 :(得分:0)

exec将返回受影响的行数:

$rows = $conn->exec($sql);

if($rows > 0){
    //suser and shashpass are correct
}else{
    //suser and shashpass are incorrect
}

答案 3 :(得分:0)

//Use below PDO code

<?php
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

echo "Connected successfully"; 
$sql = "SELECT * FROM us WHERE username='$suser' and password='$shashpass'";     
// SQL Query

$conn->exec($sql);

}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>