Mysql to PDO conversion

Asked

Viewed 91 times

-2

@$sql_usuario = "SELECT * FROM usuario ";
@$qry_usuario  = @mysql_query($sql_usuario );
@$linha_usuario  = mysql_fetch_array($qry_usuario );

Array ( [0] => 6 [u_id] => 6 [1] => 54354554[u_cod] => 54354554[2] => 54354554[u_cod] => 54354554) Array ( [0] => 17 [u_id] => 17 [1] => 323232323[u_cod2] => 3232323[2] => 3232323[u_cod2] => 3232323)

I have this query. How I would convert to PDO? The return of data is different:

@$sql_usuario  = $dbconn->prepare("SELECT * FROM usuario");
@$sql_usuario->execute();
@$linha_usuario = $sql_usuario->fetch(PDO::FETCH_ASSOC);

Array ( [u_id] => 6 [u_cod] => 54354554[u_cod] => 54354554) Array ( [u_id] => 17 [u_cod2] => 3232323[u_cod2] => 323232323)

  • I didn’t get that @ at the beginning of the variables. I posted in the answer an extremely simple example, which will assist you in the question. If you have any questions, ask.

  • @ is not to give empty index error

  • The output of the data in the case the fetchs are different understand, I would like them to follow a pattern

  • 1

    @Apprentice Yes, but there is no reason to "hide" the error, because it is a "mistake", should be treated. When to the "standard" of "fetchs" I did not understand. Edit your question, detail, exemplify.

2 answers

0

Try in PDO the following:

@$sql_usuario = $dbconn->prepare("SELECT * FROM usuario"); @$sql_usuario->execute(); @$Rows = $sql_usuario->fetchAll(PDO::FETCH_ASSOC);

0

I will post a very simple example, which will easily convert, so that you learn every detail:

Filing cabinet: config.php

date_default_timezone_set('America/Sao_Paulo');
header('Content-Type: text/html; charset=utf-8');

$user = 'root'; # Usuário do banco de dados
$pswd = '123';  # Senha

# Tentativa de conexão
try {
    $conn = new PDO('mysql:host=192.168.0.1; dbname=nomedobanco', $user, $pswd);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch(PDOException $e) {

    echo 'ERROR: ' . $e->getMessage();
}

Filing cabinet: login.php

ini_set('default_charset', 'utf-8');
require_once('config.php');

$sql = "SELECT * FROM usuarios";
$statement = $conn->prepare($sql);
$statement->execute();

# Verifica se tem ao menos 1 linha
if($statement->rowCount()) {

    # Imprimindo o retorno
    $stt = $statement->fetch(PDO::FETCH_ASSOC);
    print_r($stt);

} else {

   echo "Sem dados.";
}

Browser other questions tagged

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