How to list specific data from a table with PDO?

3

How to list specific data of a table, but using PDO ?

I'm starting to study and use PDO , but some things I can not find and that are well explained how to lite the data with a WHERE in the search.

MySQLi is used this way, but how to convert to PDO ??

$select     = mysqli_query($conn,"SELECT * FROM 'tabela' WHERE 'valor1' = '$var_1' AND 'valor2' = '$var_2'");
$aRow       = mysqli_fetch_assoc($quti_mh);
$idt        = $aRow['id'];
    
asked by anonymous 04.02.2016 / 20:10

2 answers

3

Simple queries

To make a simple query with fixed parameters or without them you can use the query () method does exactly the same thing as mysqli_query () ie it processes a query and returns a resultset that should be manipulated to extract the values.

The method that returns the database information is fetch*() it has several flavors . , arrays and objects are favorites.

fetch ()

When you need to return only one record (either to make a "change / edit") prefer fetch() it returns an array / object in the 'correct' structure do not do something like, echo $usuario[0]['nome'] , just% / p>

Return structure:

Array
(
    [id] => 1
    [nome] => Doge
    [senha] => ***
)

fetchAll ()

To return all rows of a query use $usuario['nome'] is recommended in case where there are few records.

Return structure

Array
(
    [0] => Array
        (
            [id] => 1
            [nome] => Doge
            [senha] => ***
        )

)

fetchColumn ()

Returns a scalar (ie a pure value like int, string, float etc are left out of this list arrays objects and other compound types) of a records, accepts an argument that is the index of the query column.

$db = new PDO('mysql:host=localhost;dbname=teste', 'usuario', 'senha');
//* = id, nome e senha
$query = $db->query("SELECT * FROM usuarios WHERE ativo = 1 limit 300");
$resultado = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($resultado as $item){
    $item['nome'];
}

Consultation with prepared statements

To avoid problems with sql injection prepared statements are the solution because the values sent by the user are not placed directly in the sql statement, for more details see this

$db = new PDO('mysql:host=localhost;dbname=teste', 'usuario', 'senha');
$stmt = $db->prepare("SELECT * FROM usuarios WHERE id = ?");

if(!$stmt->execute()){
    echo '<pre>';
    print_r($stmt->errorInfo());
}

$resultado = $stmt->fetch(PDO::FETCH_ASSOC);
    
05.02.2016 / 15:14
1

I think I understand what you mean, is that what you want?

$tables = $dbh->prepare("SELECT * FROM 'tabela' WHERE 'valor1' = ? AND 'valor2' = ?");

$tables->execute(array('apple', 'green'));
$resultados = $tables->fetch(PDO::FETCH_ASSOC);
    
04.02.2016 / 21:49