Skip to content

Instantly share code, notes, and snippets.

@bradsi
Last active March 30, 2021 14:16
Show Gist options
  • Save bradsi/ec1791a43812ca133f022949d1288239 to your computer and use it in GitHub Desktop.
Save bradsi/ec1791a43812ca133f022949d1288239 to your computer and use it in GitHub Desktop.
<?php
// Connect to DB
class Dbh {
private $host = "";
private $user = "";
private $pwd = "";
private $dbName = "";
protected function connect(){
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbName;
$pdo = new PDO($dsn, $this->user, $this->pwd);
// Set default return type
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
}
}
<?php
class User extends Dbh {
// Without prepared statements
public function getUsers() {
$sql = "SELECT * FROM users;";
$stmt = $this->connect()->query($sql);
while($row = $stmt->fetch()) {
echo $row['first_name'];
}
}
// With prepared statement
public function getUsersStmt($fName) {
$sql = "SELECT * FROM users WHERE first_name = ?;";
$stmt = $this->connect()->prepare($sql);
$stmt->execute([$fName]);
$names = $stmt->fetchAll();
foreach($names as $name) {
echo $name['first_name'];
}
}
// Create
public function setUserStmt($fName, $lName) {
$sql = "INSERT INTO users(first_name, last_name) VALUES (?, ?);";
$stmt = $this->connect()->prepare($sql);
$stmt->execute([$fName, $lName]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment