A very simple example connection with PHP and MySQL PDO

First we need a Data Base “Example”, with a table “products”.

//The SQL file.

CREATE DATABASE Example;

CREATE TABLE products(

id INT NOT NULL,

name VARCHAR(30) NOT NULL;

 

//Populate the table.

INSERT INTO products

VALUES

(1, John),

(2, Oscar);

 

 

//The php file.

<?php

//First we need to define the variables.
define(“DB_HOST”, “localhost”); //the local host.
define(“DB_NAME”, “Example”); //the database we need.
define(“DB_USERNAME”, “root”); //the user that we need.
define(“DB_PASSWORD”, “root”);  //the password is optional.
define(“DB_DSN”, “mysql:host=” . DB_HOST . “; dbname=” . DB_NAME . “; charset = utf8mb4”);

// Then the connection. We need a try-catch for exceptions.
try{
//PDO = PHP Data Object.
$db = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD); //Very simple.

//For possibles errors.

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

//To confirm if we are connected.
echo ‘Connected to: ‘ . DB_NAME;
}

catch(PDOException $e){
echo ‘ERROR: ‘ . $e->getMessage();
}

// The query
$query = ( “SELECT * FROM products”);

//The loop.

foreach($db->query($query) as $row){

echo $row[‘id’] . $row[‘name’];
}

?>

//