Sql command does not run via php

Asked

Viewed 952 times

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 on the label of the email, the loop always returns me ENTERED, (even if it is not registered in the bank). I already made a test to display the variable coming by the post method, and it receives exactly what I wrote in the field, but at the time of the query to the bank, this value is not used. I’ve tried many ways, but the consultation never works. This is the first time something like this has happened with my code, so if you could help me,.

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

Thanks!

  • Any error message appears?

  • no, none, apparently it works

  • Has to be mysqli? mysql does not work?

  • Var_dump() $mysqli->connect_errno : var_dump($mysqli->connect_errno); before if

  • 1

    do you want to take the password? need a fetch_array/fetch()

  • @Diegomoreira with var_dump($mysqli->connect_errno); returned int(0)

  • Yeah! In class function syntax, you can and should use simple quotes, crase does not work, break code when you run. What has to be done is a fetch_array, as @rray said. So you have access to the query return.

  • I recommend this link: https://secure.php.net/manual/en/mysqli-result.fetch-array.php

  • What you need, as a better example, you can use this: http://answall.com/questions/50919/howto get dates-de-um-select-mysqli-get-e-sent-by-newsletter I hope you get, abs

  • put $result = mysqli_fetch_array($email); and it returned: Warning: mysqli_fetch_array() expects Parameter 1 to be mysqli_result, string Given in...

Show 5 more comments

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 did not test, 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 exchange the quotation marks with simple quotation marks whenever possible and, of course, if it is easier (except for escape). PHP takes (little) longer to evaluate double quotes.

Take a look at the @utluiz response.

  • Come on, man, like I said.. I put in your code, and the idea is that the message "No results in the database for the search argument" appears, right? And when I went to test it gave the same problem of mine: I put some letters nothing to test and the message did not appear , as if I was in the bank. The server is working well, the POST too. I used the bd connection of a code that was already working. It’s really strange, but it just doesn’t use the information. I believe I’m not even making the query...

  • So I’m going to make a recommendation: use PDO. It was the best thing I’ve done to date. I’m going to post an example.

  • The table is called login even?

  • I agree with Not The Real Hemingway, PDO is the most recommended for working with the database, because in addition to having a pattern of behavior it makes several security validations (not to mention that it is already in OO).

  • Yes, it’s called login. Well I never worked with PDO, I accept the suggestion, but I would like to solve this problem with this method, after all it is not to present this kind of senseless error. I would like to know how to solve after all

  • Great then. Take the code I posted. It will print the query. Take the query and run it in Mysql. See the response of the database if there is an error.

  • I apologize. The grave accent is only for marking columns/fields. Strings are enclosed in single or double quotes in Mysql.

  • @Nottherealhemingway I did what you asked, but like all the other things I tested I gave no sign of life. This method looks interesting but unfortunately also did not work Xp

Show 3 more comments

0

We did some research based on the things you said to me and I found this link here: http://respostas.guj.com.br/20509-fazer-consulta-no-banco-de-dados-e-retornar-valores (forgive me if I can’t put links from other places) Finally 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 PDO code works I put too. Thank you for everything!

  • 1

    This only works if you use a very insecure password scheme. PHP password_hash works differently, for example. Your problem with the question is to test the validity of $res, because the fact that it does not find a user does not invalidate it. There’s a recent reply from me that gives a good example of how to use password_verify to check a password saved with password_hash, and a read on security that can help. I’ll pass the 2 links right away.

  • 2

    Example of use of password_verify: http://answall.com/a/175001/70 | Reading about safe password hashes: http://answall.com/questions/2402/70

  • Opa, I took a look there and I used the command you passed $seg_password = password_hash($password, PASWORD_DEFAULT); gave right, but now I need to know in the login part, how to make work with the password that the person type there, if you can help me thank

Browser other questions tagged

You are not signed in. Login or sign up in order to post.