Skip to content

Instantly share code, notes, and snippets.

@kiwiwr
Created October 26, 2021 19:35
Show Gist options
  • Save kiwiwr/f925baa60950e92a86812e712cc095c8 to your computer and use it in GitHub Desktop.
Save kiwiwr/f925baa60950e92a86812e712cc095c8 to your computer and use it in GitHub Desktop.

CRUD

Database connection (connect.php)

<?php
$host     = "localhost";
$dbName   = "";
$username = "";
$password = "dPowYubb";

try {
  $DBH = new PDO("mysql:host=$host;dbname=$dbName", $username, $password);
  $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $DBH->exec("set names utf8");
} catch(PDOException $e) {
    echo $e->getMessage();
    file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}

Create (create.php)

<?php
require_once 'connect.php';

$variableOne   = "";
$variableTwo   = "";
$variableThree = "";

$stmfCreate = $DBH->prepare("INSERT INTO table_name (variable_one, variable_two, variable_three) VALUES (:variableOne, :variableTwo, :variableThree)");

try {
    $stmfCreate->bindParam(':variableOne', $variableOne);
    $stmfCreate->bindParam(':variableTwo', $variableTwo);
    $stmfCreate->bindParam(':variableThree', $variableThree);
    $stmfCreate->execute();
} catch(PDOException $e) {
    echo $e->getMessage();
    file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}

Read (read.php)

<?php
require_once 'connect.php';

$id = "";
$today = date("Y-m-d H:i:s"); // Format MySQL DATETIME

$stmtRead = $DBH->query("SELECT * FROM table_name WHERE id = '$id' AND created_at = '$today'");
$stmtRead->setFetchMode(PDO::FETCH_ASSOC);

// $rowCount = $stmtRead->rowCount();

foreach ($stmtRead as $row) {
    $variableOne   = $row['variable_one'];
    $variableTwo   = $row['variable_two'];
    $variableThree = $row['variable_three'];
}

Update (update.php)

<?php
require_once 'connect.php';

$variableOne   = "";
$variableTwo   = "";
$variableThree = "";

$stmfUpdate = $DBH->prepare("UPDATE table_name SET variable_one = (:variableOne), variable_two = (:variableTwo), variable_three = (:variableThree)");

try {
    $stmfUpdate->bindParam(':variableOne', $variableOne);
    $stmfUpdate->bindParam(':variableTwo', $variableTwo);
    $stmfUpdate->bindParam(':variableThree', $variableThree);
    $stmfUpdate->execute();
} catch(PDOException $e) {
    echo $e->getMessage();
    file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}

Delete (delete.php)

<?php
require_once 'connect.php';

$id = "";

try {
    $stmfDelete = $DBH->prepare("DELETE FROM table_name WHERE id = :id");
    $stmfDelete->bindParam(':id', $id);
    $stmfDelete->execute();
} catch(PDOException $e) {
    echo $e->getMessage();
    file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment