PHP & MySQL
Tenzij anders aangegeven, gebruikt dit artikel PDO voor database-connecties.
Drivers
MySQLi
enPDO
lijken anno 2019 de twee belangrijkste drivers/API's te zijnmysql_
is oud en begraven- Daarnaast bestaan er ook voor PHP ORM's
PDO
- Generiek voor diverse databases - Boeit niet, want ik gebruik momenteel alleen MySQL
- Niet zo up-to-date als MySQLi
- "A really nice thing with PDO is you can fetch the data, injecting it automatically in an object. If you don't want to use an ORM (cause it's a just a quick script) but you do like object mapping, it's REALLY cool" [1]
MySQLi
- Meer up-to-date
- Primitiever
Conclusie (april 2019)
Connect (PDO)
Voorbeeld:
<?php ############################################################### # Connect with dwh through PDO ############################################################### # $servername = "localhost"; $dbname = "example"; $username = "supervrouw"; $password = "geheim"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); # set the PDO error mode to exception ##################################### # $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully\n"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage()."\n"; }
Fetch data
Soms, soms is het leven verrassend eenvoudig [5]:
############################################################### # Fetch & process table "product_tmp" ############################################################### # $sql = $conn->prepare("select * from product_tmp"); $sql->execute(); $rows = $sql->fetchAll(); foreach ($rows as $row) { echo $row['sku']."\n"; }
Tekencodering
Argh! Duitse umlauten gaan om zeep als je niet oppast. De oplossing: In de connection string aangeven wat de tekencodering is, die je in de db gebruikt (en als die verschilt van tabel tot tabel? Geen idee). Voorbeeld [6]:
$conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password);