ryoakg
7/7/2016 - 1:49 PM

サンプルコード

サンプルコード

<?php
if (PHP_SAPI !== 'cli') throw new Exception(PHP_SAPI . ' is not supported SAPI.');

function usage($msg = NULL) {
    if ($msg) echo $msg . PHP_EOL;
    $script_name = $_SERVER['PHP_SELF'];
    echo "usage: php ${script_name} setup|show|insert|update|delete" . PHP_EOL;
    exit();
};

function extract_arguments ($argv) {
    $a = array();
    $er = error_reporting();
    error_reporting(E_ALL & ~E_NOTICE);
    if (! $a['task'] = $argv[1]) usage('TASK is not provided!');
    error_reporting($er);
    return $a;
}
extract(extract_arguments($argv));

function setup(){
    $pdo = new PDO('sqlite:test.db');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $pdo->prepare("
CREATE TABLE test (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT
)");
    $stmt->execute(array());
}

function show(){
    $pdo = new PDO('sqlite:test.db');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

    $stmt = $pdo->prepare('SELECT * FROM test');
    $stmt->execute(array());
    var_dump($stmt->fetchAll());
}

function insert(){
    $pdo = new PDO('sqlite:test.db');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $pdo->prepare("INSERT INTO test (name) values (?)");
    $stmt->execute(array(substr(str_shuffle(join(array_merge(range('a','z'),range('0','9')))),
                                0, mt_rand(8, 20))));
}

function update(){
    $pdo = new PDO('sqlite:test.db');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $pdo->prepare("UPDATE test SET name = ?");
    $stmt->execute(array(substr(str_shuffle(join(array_merge(range('a','z'),range('0','9')))),
                                0, mt_rand(8, 20))));
}

function delete(){
    $pdo = new PDO('sqlite:test.db');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $pdo->prepare("DELETE FROM test;");
    $stmt->execute(array());
}

switch(true){
case $task === 'setup':
    return setup();
case $task === 'show':
    return show();
case $task === 'insert':
    return insert();
case $task === 'update':
    return update();
case $task === 'delete':
    return delete();
}
return $usage();