Simple PDO Connection and select


/ Published in: PHP
Save to your folder(s)

This is the basic code that you need to know to connect and list data with PDO.
Don't use de old method (mysql_connect and mysqli_connect) to connect and interact with databases.


Copy this code and paste it in your HTML
  1. <?php
  2. /* Connection string */
  3. $db = new PDO('mysql:host=localhost;dbname=YOUR_DB_NAME', 'root', 'YOUR_DB_PASSWORD', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
  4.  
  5. $stmt = $db->prepare('select * from your_table');
  6. $stmt->execute();
  7.  
  8. // Get all records
  9. $result = $stmt->fetchAll();
  10.  
  11. echo '<pre>';
  12. print_r($result); // Show a data array with results

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.