Skip to content

Instantly share code, notes, and snippets.

@JeffreyWay
Created October 26, 2022 17:29
Show Gist options
  • Select an option

  • Save JeffreyWay/2371cd20b38888ef67241e228723deab to your computer and use it in GitHub Desktop.

Select an option

Save JeffreyWay/2371cd20b38888ef67241e228723deab to your computer and use it in GitHub Desktop.
<?php
// Connect to the MySQL database.
$dsn = "mysql:host=localhost;port=3306;dbname=myapp;user=root;charset=utf8mb4";
// Tip: This should be wrapped in a try-catch. We'll learn how, soon.
$pdo = new PDO($dsn);
$statement = $pdo->prepare("select * from posts where id = 1");
$statement->execute();
$post = $statement->fetch(PDO::FETCH_ASSOC);
echo "<li>" . $post['title'] . "</li>";
<?php
require 'functions.php';
// Connect to the MySQL database.
$dsn = "mysql:host=localhost;port=3306;dbname=myapp;user=root;charset=utf8mb4";
// Tip: This should be wrapped in a try-catch. We'll learn how, soon.
$pdo = new PDO($dsn);
$statement = $pdo->prepare("select * from posts");
$statement->execute();
$posts = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach ($posts as $post) {
echo "<li>" . $post['title'] . "</li>";
}
@MatimotTheTimoters
Copy link

<?php

require 'functions.php';

// Connect to MySQL DB
$dsn = "mysql:host=localhost;port=3306;dbname=myapp;charset=utf8mb4";
$username = 'root';
$password = 'mypassword';
$pdo = new PDO($dsn, $username, $password);

// Create retrieve query
$statement = $pdo->prepare("SELECT * FROM posts");
$statement->execute();

// Fetch records
$posts = $statement->fetchAll(PDO::FETCH_ASSOC);

// Display results
foreach ($posts as $post) {
    echo "<li>{ $post['title'] }</li>";
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment