Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Aprendendo instruções preparadas SELECT FROM WHERE


Olá ButterDog, deixe-me orientá-lo passo a passo no PDO.

Passo 1)

crie um arquivo chamado connect.php (ou o que você quiser). Este arquivo será necessário em cada arquivo php que requer interações com o banco de dados.

Vamos começar também, observe meus comentários:
?php

//We set up our database configuration
$username="xxxxx"; // Mysql username
$password="xxxxx"; // Mysql password


// Connect to server via PHP Data Object
$dbh = new PDO("mysql:host=xxxxx;dbname=xxxxx", $username, $password); // Construct the PDO variable using $dbh
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set attributes for error reporting very IMPORTANT!
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE); // Set this to false so you can allow the actual PDO driver to do all the work, further adding abstraction to your data interactions.
?>

Passo 2) Requer o connect.php por favor dê uma olhada:
require ('....../........./...../connect.php'); // Require the connect script that made your PDO variable $dbh

Etapa 3)

para iniciar as interações com o banco de dados, faça o seguinte também, leia os comentários do código. Por enquanto não vamos nos preocupar com arrays! Obtenha o resumo completo do PDO e preocupe-se em facilitar o trabalho! Com a repetição do "longo caminho" vem mais compreensão do código. Não corte cantos para começar, corte-os quando entender o que está fazendo!
$query = $dbh->prepare("SELECT * FROM note_system WHERE note = :cnote"); // This will call the variable $dbh in the required file setting up your database connection and also preparing the query!

$query->bindParam(':cnote', $cnote); // This is the bread and butter of PDO named binding, this is one of the biggest selling points of PDO! Please remember that now this step will take what ever variable ($cnote) and relate that to (:cnote)

$query->execute(); // This will then take what ever $query is execute aka run a query against the database

$row = $query->fetch(PDO::FETCH_ASSOC); // Use a simple fetch and store the variables in a array

echo $row['yourvalue']; // This will take the variable above (which is a array) and call on 'yourvalue' and then echo it.

Isso é tudo que existe para PDO. Espero que tenha ajudado!

Veja também este . Isso me ajudou tanto!

Eu também uso este como referência (às vezes) - O site parece uma porcaria, mas há informações de qualidade sobre PDO lá. Eu também uso este e eu juro que este é o último link! Então, depois disso, qualquer dúvida é só perguntar, mas espero que isso possa se transformar em um pequeno guia de referência sobre PDO. (espero rs)