How can I correctly use a PDO object for a selection query

Asked

Viewed 84 times

-2

i followed the recommendations of php.net, to make a select in a certain database using PDO, however I do not know if I am doing it the right way, I wonder if you can help me

$duosig = "SELECT NOMCLI FROM SINAF019";
$stm = $lokos->query($duosig);
$stm->execute();
echo $NOMCLI;
  • in the case there $nomcli, it would be $Row['NOMCLI'];

1 answer

2

You receive the data from statement, through the method fetch:

$row = $stm->fetch(PDO::FETCH_ASSOC);

On the blog Devmedia, has an article Introduction to PHP PDO, that would be a good read.

$stmt = $con->prepare("INSERT INTO pessoa(nome, email) VALUES(?, ?)"); 
$stmt->bindParam(1, "Nome da Pessoa");  // Altera o primeiro "?" da query para "Nome da Pessoa"
$stmt->bindParam(2, "[email protected]");  // Altera o segundo "?" da query para "[email protected]"
$stmt->execute(); // Executa a query

$rs = $con->query("SELEC idpessoa, nome, email FROM pessoa"); // Busca os dados no banco
while($row = $rs->fetch(PDO::FETCH_OBJ)){ // Lê uma linha de cada vez
   echo $row->idpessoa . "<br />"; 
   echo $row->nome . "<br />"; 
   echo $row->email . "<br />"; 
}

Applying the knowledge in your case:

$duosig = "SELECT NOMCLI FROM SINAF019"; // SQL
$rs = $lokos->query($duosig); // Executa a query
$row = $rs->fetch(PDO::FETCH_OBJ) // Recebe uma linha de dados
echo $row->NOMCLI; // Imprime um dados

To receive multiple rows of data put the expression fetch in a loop

while($row = $rs->fetch(PDO::FETCH_OBJ)){
  // Use os dados $row->NOMECOLUNA
}

In case you’re applying for an enclosure Where, always use the prepare:

$stmt = $con->prepare("SELECT NOMCLI FROM SINAF019 WHERE ID = ?"); 
$stmt->bindParam(1, 5, PDO::PARAM_INT); // Altera o primeiro "?" para "5"
$stmt->execute(); // Executa o statement
$row = $stmt->fetch(PDO::FETCH_OBJ) // Recebe uma linha de dados
echo $row->NOMCLI; // Imprime um dados

Browser other questions tagged

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