Table of Contents

Teaching PHP

Making a MySQL database connection

$host = "localhost";
$dbname = "database_name";
$username = "username";
$password = "password";
$port = 3306;
$charset = "utf8mb4";
 
$connection_string = "mysql:host=$host;dbname=$dbname;port=$port;charset=$charset";
$db_settings = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING,
                     PDO::ATTR_PERSISTENT => true);
 
$db = new PDO($connection_string, $username, $password, $db_settings);

Fetching data

$sql = "select * from tablename";
$stmt = $db->query();
$data = $stmt->fetchall();

Fetching specific data

$search_term = "Neil";
$sql = "select * from tablename where forename=?"
$stmt = $db->prepare($sql);
$stmt->execute([$search_term]);
$data = $stmt->fetch();

Inserting data

$test_var = 123;
$sql = "insert into tablename set var1=?";
$stmt = $db->prepare($sql);
$stmt->execute([$test_var]);