Validate data with PDO

3

I'm migrating my php code in which I was using sql query for PDO, but I'm finding it difficult to validate data with this.

NOTE: I already have a functional file that searches the database, my difficulty is really to compare it with POST and validate it.

NOTE: If someone can pass me a link to assist in migrating from mysql_ to PDO it would help a lot!

Here is the php code I'm trying to work with:

if(isset($_POST['entrar']) && $_POST['entrar'] == "login"){
    $ID = $_POST['usuario'];
    $senha = $_POST ['senha'];
    if (empty($ID) || empty ($senha)){
        echo '<p style="font: 20px Verdana; position:absolute; top:700px; left:40%; color:red;">Por favor preencha os campos!</p>';
    }
    else{
        $buscar=$pdo->prepare("SELECT ID, senha, usuario FROM usuarios WHERE ID='$ID' AND senha='$senha'");
        $buscar->execute();
        $linha=$buscar->fetchALL(PDO::FETCH_ASSOC);
        foreach ($linha as $listar){
        if ($listar >0){
            $_SESSION['ID'] = $busca ['ID'];
            $_SESSION['usuario'] = $busca ['usuario'];
            header ('location:logado.php');
            exit;
        }
        else{
            echo '<p style="font: 30px Verdana;  text-align:center; color:red;">Usuario ou senha invalidos.';
            echo '<meta http-equiv="refresh" content="1;URL=index.html" />';
        }
    }
}
    
asked by anonymous 20.09.2017 / 17:03

1 answer

3

Who has the result of the query $linha and not $busca . If you are going to return only one record use fetch() instead of fecthAll() this eliminates an unnecessary foreach.

if(!empty($_POST['entrar']) && $_POST['entrar'] == "login"){
    if (empty($_POST['usuario']) || empty ($_POST['senha'])){
        echo '<p style="font: 20px Verdana; position:absolute; top:700px; left:40%; color:red;">Por favor preencha os campos!</p>';
    }else{
        $buscar = $pdo->prepare("SELECT ID, senha, usuario FROM usuarios WHERE ID = ? AND senha = ?");
        $buscar->execute(array($_POST['usuario'], $_POST ['senha']));
        $linha = $buscar->fetch(PDO::FETCH_ASSOC);

        if($buscar->rowCount()){
            $_SESSION['ID'] = $linha['ID'];
            $_SESSION['usuario'] = $linha['usuario'];
            header ('location:logado.php');
            exit;
        }else{
             echo '<p style="font: 30px Verdana;  text-align:center; color:red;">Usuario ou senha invalidos.';
            echo '<meta http-equiv="refresh" content="1;URL=index.html" />';
        }
    }
}
    
20.09.2017 / 17:21