note 127613 added to class.pdo
| From: | Ahmedalahned at main dot php dot net | Date: | Mon, 12 Sep 2022 18:50:38 +0000 |
| Subject: | note 127613 added to class.pdo | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-219557@lists.php.net to get a copy of this message | ||
Simple Example for a PDO Database Connection because i cant find one
<?php
class Database
{
private static $dbName = 'dataBaseName';
private static $dbHost = 'localhost';
private static $dbUsername = 'root';
private static $dbUserPassword = '';
private static $conn = null;
public function __construct()
{ exit('Init function is not allowed'); }
public static function connect()
{ // One connection through whole application
if (null == self::$conn) {
try {
self::$conn = new PDO("mysql:host=" . self::$dbHost . ";" .
"dbname=" . self::$dbName . ';charset=utf8mb4',
self::$dbUsername,
self::$dbUserPassword);
} catch (PDOException $e) {
die($e->getMessage());
}
}
self::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return self::$conn;
}
public static function disconnect()
{ self::$conn = null; }
}
?>
//Create
public function create()
{
$db = Database::connect();
$sql = "INSERT INTO databaseName (firstname, lastname) values( ?, ?)";
$stmt = $db->prepare($sql);
$stmt->execute(array($this->firstName, $this->lastName ));
$lastId = $db->lastInsertId(); // get ID of new database-entry
Database::disconnect();
return $lastId;
}
//Read
public static function get($id)
{
$db = Database::connect();
$sql = "SELECT * FROM tableName WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->execute(array($id));
// fetch dataset (row) per ID, convert to Credentials-object (ORM)
$item = $stmt->fetchObject('table');
Database::disconnect();
return $item !== false ? $item : null;
}
//update
public function update()
{
$db = Database::connect();
$sql = "UPDATE credentials set firstName = ?, lastName = ? WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->execute(array($this->firstName, $this->lastName));
Database::disconnect();
}
//Delete
public static function delete($id)
{
$db = Database::connect();
$sql = "DELETE FROM credentials WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->execute(array($id));
Database::disconnect();
}
----
Server IP: 45.112.84.4
Probable Submitter: 185.85.3.173 (proxied: 185.40.54.167)
----
Manual Page -- https://php.net/manual/en/class.pdo.php
Edit -- https://main.php.net/note/edit/127613
Del: integrated -- https://main.php.net/note/delete/127613/integrated
Del: useless -- https://main.php.net/note/delete/127613/useless
Del: bad code -- https://main.php.net/note/delete/127613/bad+code
Del: spam -- https://main.php.net/note/delete/127613/spam
Del: non-english -- https://main.php.net/note/delete/127613/non-english
Del: in docs -- https://main.php.net/note/delete/127613/in+docs
Del: other reasons-- https://main.php.net/note/delete/127613
Reject -- https://main.php.net/note/reject/127613
Search -- https://main.php.net/manage/user-notes.php