Last active
March 30, 2021 14:16
-
-
Save bradsi/ec1791a43812ca133f022949d1288239 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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