PDO: Connecting Use PHP Data Object


PHP Data Objects (PDO) Step By Step Tutorial - Part 3: Now, we test to connect to database. We use mysql server. Before test, please create a database named "test". Then create table "books" with query like this:
CREATE TABLE `books` (
  `id` int(11) NOT NULL auto_increment,
  `title` varchar(150) NOT NULL,
  `author` varchar(150) NOT NULL,
  `description` varchar(255) NOT NULL,
  `on_sale` tinyint(1) NOT NULL,
  PRIMARY KEY  (`id`)
);

Following query for sample data:

INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (1, 'PHP AJAX', 'Andreas', 'This is good book for learning AJAX', 1);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (2, 'PHP Eclipse ', 'George', 'Nice book', 0);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (3, 'PHP Prado', 'Junyian', '-', 1);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (4, 'PHP Zend Framework', 'Ozulian', 'great', 0);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (5, 'PHP Web Services', 'Bobi', '', 0);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (6, 'PHP API', 'Hugo', '', 1);
INSERT INTO `books` (`id`, `title`, `author`, `description`, `on_sale`) VALUES (7, 'PHP SEO', 'Monteo', '', 1);

Now, this is sample connection to mysql database:

<?php
$host 	= "localhost";
$db	= "test";
$user	= "root";
$pass	= "admin";

$conn = new PDO("mysql:host=$host;dbname=$db",$user,$pass);

$sql = "SELECT * FROM books";
$q	 = $conn->query($sql) or die("failed!");
while($r = $q->fetch(PDO::FETCH_ASSOC)){
  echo $r['title'];
}


?>

Previous: PDO: Activation PHP Data Objects Extension
Next: PDO: Portable Connection to Database



Series this article:
PDO: Introduction PHP Data Object
PDO: Activation PHP Data Objects Extension
PDO: Connecting Use PHP Data Object
PDO: Portable Connection to Database
PDO: Posibble Fetch Mode
PDO: Error Handling
PDO: Prepared Statement
PDO: Positional and Named Placeholders
PDO: Insert and Update Statement Use Prepared Statement
PDO: Prepared Statement and Bound Values
PDO: Working With BLOBs
PDO: Alternative Retrieve BLOB Data
PDO: Setting Connection Attributes
PDO: Error Mode Attributes
PDO: Improve Performance with Persistent Connection
PDO: Getting Connection Attributes

Bookmark and Share Tag: PHP Data Objects, PDO, extension, PHP extension, database connection Category: PHP Database Post : April 18th 2008 Read: 80,518

advertisements


blog comments powered by Disqus