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>";
}
@AdolpheNkoranyiTresor
Copy link

AdolpheNkoranyiTresor commented Jun 29, 2023

require 'functions.php';

// require 'router.php';

//connect to our MySQL database

// Created a prepared statement to fetch data in test(test is my db table name) that has an id of 1. Then, experimented with calling fetch() instead of fetchAll()

$dsn = "mysql:host=localhost;port=3306;user=root;dbname=firstphp;charset=utf8mb4";
$pdo = new PDO($dsn);

$statement = $pdo->prepare("SELECT * From test WHERE id = 1");
$statement->execute();

$test = $statement->fetch(PDO::FETCH_ASSOC);

echo "<li>" . $test['user_name'] . " " . $test['email'] . "</li>";

@NyiNyiAung16
Copy link

NyiNyiAung16 commented Oct 21, 2023

//connection with mysql
$dns = "mysql:host=localhost;dbname=myapp;user=root;charset=utf8mb4";

$pdo = new PDO($dns);

$statement = $pdo->prepare("select * from posts where id=1");
$statement->execute();
$post = $statement->fetch(PDO::FETCH_ASSOC);

echo "

  • ".$post['title']."
  • ";

    @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