Connecting to a MySQL Database with the PHP library PDO
PDO stands for PHP Data Objets and support Prepared Statements
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php $id = 3; //let's wrap everything within a try/catch block try { $pdo = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password); $query = $pdo->prepare('SELECT * FROM myTable WHERE id = :id'); //set the ATTR_ERRMODE and ERRMODE_EXCEPTION to see if something goes wrong $pdo-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $query = $pdo->prepare('SELECT * FROM myTable WHERE id = :id'); $query->execute(array( 'id' => $id )); while ($row = $query->fetch()) { //you can get an object instead of an array by using: //while($row = $stmt->fetch(PDO::FETCH_OBJ)) print_r($row); } } catch (PDOException $e) { echo 'ERROR: '.$e - > getMessage(); } ?> |
you can also use the bindParam method, like:
1 2 |
$query-> bindParam(':id', $id, PDO::PARAM_INT); $query-> execute(); |