Single user name and password converting mysql_ * to PDO

-3

I need to update a legacy code and for that I need to make two modifications to it.

The first modification is to abandon the mysql_* functions and use the PDO.

The second is to update the database so that I can not register two user names and passwords with the same values.

Code that looks for Nome and imgPerfil of a user:

<?php 

require_once "includes/config.php";

$Usuario = $_SESSION["Usuario"];
$Senha   = $_SESSION["Senha"];

$SQL = mysql_query("SELECT Nome, imgPerfil FROM administradores WHERE Usuario=$Usuario' AND Senha='$Senha' ");

Code that takes user values:

<?php 

while($Linha = mysql_fetch_assoc($SQL)) {
    $nomeUser = $Linha['Nome'];
    $imgpUser = $Linha['imgPerfil'];
}

Code that prints the values:

<?php echo $nomeUser; ?>

and

<?php echo $imgpUser; ?>
    
asked by anonymous 26.12.2014 / 09:45

1 answer

4

To avoid duplicate values set the column as the unique key direct by the bank.

ALTER TABLE tabela ADD CONSTRAINT UNIQUE (campo)

To convert code with PDO and prepared statements

$db = new PDO('mysql:host=localhost;dbname=teste',$usuario_db, $senha_db);

$sql = 'SELECT Nome, imgPerfil FROM administradores 
        WHERE Usuario= :usuario AND Senha =:senha';

$stmt = $db->prepare($sql);
$stmt->bindValue(':usuario', $usuario);
$stmt->bindValue(':senha', $senha);

$stmt->execute();
$item = $stmt->fetch(PDO::FETCH_ASSOC); //retorna apenas uma linha
echo $item['Nome'] .' - '. $item['imgPerfil'];
    
26.12.2014 / 10:35