Problems with PDO

Asked

Viewed 205 times

1

I’m new with PHP and would like to ask a question:

In the code that I will show below, has been tested the consultation in the bank until the try, the problem is that after the try(){} the prepare does not return me anything, I tested with the die(''); and he only returns to me echo and only goes so far.

Follow the login.php code

<?php
require_once("connect.php");
//recuperar dados
if(isset($_POST['logar'])){
    echo 'clciou</br>';
    echo   $usuario= trim(strip_tags($_POST['usuario']));
    echo   $senha= trim(strip_tags($_POST['senha']));
    $select="SELECT*FROM login WHERE usuario=:usuario AND senha=:senha";
    echo $contar = $selec-> rowCount();
    try{
        $result = $conexao ->prepare($select);
        $result -> bindParam(':usuario',$usuario,PDO::PARAM_STR);
        $result -> bindParam(':senha',$senha,PDO::PARAM_STR);
        $result -> execute();
    }
    catch(PDOException $e){
        echo $e;
    }
}
?>

Form he picks up

<form action="#" method="post" enctype="multipart/form-data">
  <h1>Faça seu Login</h1>
  <div class="login-fields">
    <p>Entre com seus dados:</p>
    <div class="field">
      <label for="username">Usuário:</label>
      <input type="text" id="username" name="usuario" value="" placeholder="Usuário" class="login username-field" />
    </div>
    <!-- /field -->
    <div class="field">
      <label for="password">Senha:</label>
      <input type="password" id="password" name="senha" value="" placeholder="Senha" class="login password-field" />
    </div>
    <!-- /password -->
  </div>
  <!-- /login-fields -->
  <div class="login-actions">
    <input type="submit" name="logar" value="entrar no sistema" class="button btn btn-success btn-large" />
  </div>
  <!-- .actions -->
</form>

Could someone tell me what I do wrong?

  • 1

    See if there are any errors: if(! $result -> execute()){ print_r($result->errorInfo());

  • I edited the post to make it easier to understand.

  • Thank you Father, but so, I used and he did not inform me anything.

  • The error was this : Fatal error: Call to a Member Function prepare() on null in /var/www/html/Chris/login.php

  • You have prompted $connected ? in case it should be an instance of PDO, have how to put as this the class connect.php?

  • Hello boy! What’s this for? " echo $usuario= Trim(strip_tags($_POST['user']));" and that? " echo $password= Trim(strip_tags($_POST['password']));" Do you want to use the variable or print it? The right would be: $usuario= Trim(strip_tags($_POST['usuario'])); and $password= Trim(strip_tags($_POST['password']));

Show 1 more comment

1 answer

0


Hello boy look there the solution:

<?php
require_once("connect.php");

//recuperar dados
if(isset($_POST['logar']) == true){
echo 'clicou</br>';
//Melhor seria usar Expressões regulares aqui, é mais seguro        
//seria bom também passar o htmlentities($var, ENT_QUOTES | ENT_HTML5, 'UTF-8', false)
// nos campos e converter tudo para utf-8, o "false" diz à função que
// não tente converte se já estiver no formato utf-8
$usuario= trim(strip_tags($_POST['usuario']));
$senha= trim(strip_tags($_POST['senha']));

// Executar a instrução SQL     
$sql = "SELECT * FROM login WHERE nome = :usuario AND senha = :senha";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':usuario', $usuario,PDO::PARAM_STR);
$stmt->bindParam(':senha', $senha,PDO::PARAM_STR);

$stmt->execute();
// Se encontrar algumacoisa '$stmt->rowCount() > 0', continuar
if($stmt->rowCount() > 0 ){

//Percorrendo todos os registros encontrados
for($i=0; $row = $stmt->fetch(); $i++){
//Imprime o ID e nome do Usuário                
echo "O id &eacute;:".$row['id'].", o nome &eacute;:".$row['nome']."<br />";
}
} else {
//Caso não encontre nada escreva "Nadinha!" ou algo mais inteligente
echo "Nadinha!";
}
}
?>

This Tray is in connect. I eutentei this way there and it does not go at all. Regarding this file "connect.php", it should be exactly like this:

<?php
//File connect.php
$dsn = 'mysql:host=localhost;dbname=nomedoseudatabase';
$user = 'usuariododatabase';
$password = 'senhadosusuariododatabase'; 
try {
//instaciar o objeto PDO    
$pdo = new PDO($dsn, $user, $password);
// adicionar suporte a utf-8
$pdo->exec("SET NAMES 'utf8' COLLATE 'utf8_general_ci'");
//dizer ao pdo o que fazer em caso de erro
} catch (PDOException $e) {echo 'Conexao sem sucesso: ' . $e->getMessage(); }
?>

I had to do this table in my Slackware db here to test, ta working right.

I think you should be in the habit of making a class for the database or classes. On my site I use several databases, users, Sesssions and user profiles and preferences stay in the same database. Already posts and other things that are put on the site stay in another and everything works round. He picks up the posts and, when running over each post, he queries the other database and picks up everything about the user, including social networks if he has registered and puts the schemas in the post for indexing in Google. If the guy is logging in, he even queries the profile table automatically because the login class calls the profile class to which he checks if the person has a profile on the site and if he has put all user preferences on Section and this can be accessed by the whole site so that he no longer needs to put names on forms, because there are no fields for name and email if the person is logged in. Classes make things very simple. Hugging boy! Good studies!

Browser other questions tagged

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