per creare la connessione
try {
$db = new PDO("mysql:dbname=".DB_NAME.";host=".DB_HOST,DB_USER,DB_PWD);
} catch (PDOException $e) {
die("Database Connection Failed: " . $e->getMessage());
}
Poi per preparare una dichiarazione
$prep = $db->prepare("SELECT * FROM `users` WHERE userid = ':id'");
Come si può vedere, si etichetta ogni parametro vuoi anteponendo qualsiasi stringa con ':'. Quindi tutto ciò che fai è passare un array mappando il parametro (: id) al valore quando esegui.
if (!$prep->execute(array(":id" => $userinput))) {
$error = $prep->errorInfo();
echo "Error: {$error[2]}"; // element 2 has the string text of the error
} else {
while ($row = $prep->fetch(PDO::FETCH_ASSOC)) { // check the documentation for the other options here
// do stuff, $row is an associative array, the keys are the field names
}
}
Invece di PDO :: FETCH_ASSOC con la funzione "fetch", ci sono vari altri modi per ottenere i vostri dati. Puoi usare fetchAll per ottenere un array di TUTTI i risultati contemporaneamente anziché solo fila per riga. Oppure puoi ottenere la matrice di informazioni come una matrice indicizzata 0, o puoi anche recuperare i risultati direttamente in un'istanza di classe (se i nomi dei campi sono allineati con le proprietà della classe.)
Tutta la documentazione di DOP può essere trovato qui: PHP.net PDO Manual
Credo che non ti servano le virgolette attorno a un segnaposto: "SELECT * FROM \' users \ 'WHERE userid =: id" ' –