sql command does not run via php

1

I'm having a problem with my bd query. I want to make a login page with the following form:

 <form method="post" action="Login.php">
   Email:<br>
   <input class="form-control" placeholder="Seu email" type="text" name="email">
   <br>
   Senha:<br>
   <input class="form-control" type="password" placeholder="Sua senha" name="senha">
   <br>
   <input type="submit" class="btn btn-embossed btn-info" name="Entrar" value="Entrar">
</form>

And use the Login.php page:

<?php
//Conectando ao banco de dados
$mysqli = new mysqli("localhost", "root", "", "authenticationteste");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;
}

//$nomeUser = $_POST["nomeUser"];
$email = $_POST["email"];
//$senha = $_POST["senha"];
//Consultando banco de dados
$res   = $mysqli->query("SELECT senha FROM login WHERE email='".$email."';");

//email não encontrado
if (!$res) {
    echo "Query failed: (".$mysqli->errno.") ".$mysqli->error;
}

However, when I put any information in the email label, the loop always returns me ENTROU, (even if it is not registered in the database). I've done a test to display the variable coming from the post method, and it gets exactly what I wrote in the field, but at the time of the database query, that value is not used. I have tried many ways, but the query never works. This is the first time something like this happens with my code, so if you can help I appreciate it.

I repeat: The post method is working, it stores in the variable correctly. the problem is time to use it in the query.

Thank you!

    
asked by anonymous 10.01.2017 / 20:07

2 answers

1

Editing

Example with PDO

<?php
// Primeira coisa: recebe os cabeçalhos e envia
$email = $_POST["email"];

// Tenta trazer os dados do banco de dados
try {
    // Cria objeto PDO
    $conexao = new PDO('mysql:host=localhost;dbname=authenticationteste', 'root', '');

    // Query que será executada. Recebe o parâmetro :email
    $query = "select senha from login where email= :email";

    // Prepara a query para execução
    $consulta = $conexao->prepare($query, array(PDO::CURSOR_SCROLL));

    // Atribui o parametro $email a :email na consulta
    $consulta->bindParam(':email', $email);

    // Executa a consulta ao banco de dados
    $consulta->execute();

    // Conta quantaslinhas foam retornadas do banco de dados
    $numero_linhas = $consulta->rowCount();

    // Se tiver pelo menos uma linha, retorna os valores...
    if($numero_linhas !== 0){
        $resultado = $consulta->fetchAll(PDO::FETCH_ASSOC);

        // Faça o que bem entender com o resultado
        // você pode usar:
        /**
         while($resultado = $consulta->fetch(PDO::FETCH_ASSOC)){
             echo $resultado['coluna_desejada']
         }
         */
    } else {
        echo "Nenhum resultado no banco de dados para o argumento de pesquisa";
    }

} catch (Exception $ex) {
    echo "Deu ruim: ".$ex->getMessage();
}

I have not tested, because I only have SQL Server here, but here it goes:

<?php
// Primeira coisa: recebe os cabeçalhos e envia
$email = $_POST["email"];

// Tenta trazer os dados do banco de dados
try {
    // Conexão com o banco de dados
    $mysqli = new mysqli("localhost", "root", "", "authenticationteste");

    // Consulta o banco de dados
    //TODO: escapar as strings !IMPORTANTE

    $query = 'select senha from login where email="'.$email.'"';

    // Imprime informações sobre a query
    var_dump($query);

    $resultado = $mysqli->query($query);

    if ($resultado->num_rows == 1) {
        $linha = $resultado->fetch_assoc();
        // Faça o que quiser com o resultado usando, por exemplo, $linha['senha']
    } else {
        echo "Nenhum resultado no banco de dados para o argumento de pesquisa";
    }

    $mysqli->close();
} catch (Exception $ex) {
    echo "Deu ruim: ".$ex->getMessage();
}

Depending on the complexity of the code, I would also change the double quotes in single quotation marks whenever possible, and of course, if it is easier (except for escape). PHP takes (a little) longer to evaluate double quotes.

Gives a look at the answer from @ utluiz ♦.

    
10.01.2017 / 20:53
0

I did some research based on the things you said to me and I found this link here: link (please forgive me if you can not put links from other places) Anyway, it ended up like this:

<?php
$con = mysqli_connect("localhost","root","","authenticationteste") or die(mysql_error());

$email = $_POST["email"];
$senha = $_POST["senha"];

$query = mysqli_query($con,"SELECT senha from login where email = '$email'")or die(mysql_error());
$numrow = mysqli_num_rows($query);
    if($numrow > 0){
        while($row=mysqli_fetch_array($query)){
            if($row['senha'] == $senha){ 
                echo"<script>alert('Login valido');</script>";
            }else{
                echo "<script>alert('Login e inválidos');</script>";
            }
        }// fim do while         
    } 

? >

If I find out how the code works in PDO I put it as well. Thank you for all people!

    
10.01.2017 / 22:12