Python DB-API

Python DB-API is a library method call sqlite and data.

writing DB-API

import sqlite3
conn = sqlite3.connect("Cookies")
cursor = conn.cursor()
cursor.execute(
    "select host_key from cookies limit 10")

results = cursor.fetchall()
print results
conn.close()

Watch how DB-API work below.

import sqlite3

# Fetch some student records from the database.
db = sqlite3.connect("students")
c = db.cursor()
query = "select name, id from students;"
c.execute(query)
rows = c.fetchall()

# First, what data structure did we get?
print "Row data:"
print rows

# And let's loop over it too:
print
print "Student names:"
for row in rows:
  print "  ", row[0]

db.close()

Result
Row data:
[(u’Jade Harley’, 441304), (u’Harry Evans-Verres’, 172342), (u’Taylor Hebert’, 654321), (u’Diane Paiwonski’, 773217), (u’Melpomene Murray’, 102030), (u’Robert Oliver Howard’, 124816), (u’Hoban Washburne’, 186753), (u’Trevor Bruttenholm’, 162636), (u’Jonathan Frisby’, 917151)]

Student names:
Jade Harley
Harry Evans-Verres
Taylor Hebert
Diane Paiwonski
Melpomene Murray
Robert Oliver Howard
Hoban Washburne
Trevor Bruttenholm
Jonathan Frisby

order by [ASC | DESC]

sql join on

QUERY = '''
select animals.name 
from animals join diet on animals.species = diet.species
where food = 'fish';
'''

having

QUERY = '''
select species, count(*) as num 
from animals group by species
having num = 1;
'''
QUERY = '''
select species, count(*) as num 
from animals group by species
having num = 1;
'''

QUERY = '''
select diet.food, count(*) as num
from animals join diet on animals.species = diet.species
group by food
having num = 1;
'''

python sql

QUERY = '''
select name, birthdate from animals where species = 'gorilla';
'''

+———+————+
| name | birthdate |
+=========+============+
| Max | 2001-04-23 |
| Dave | 1988-09-29 |
| Becky | 1979-07-04 |
| Liz | 1998-06-12 |
| George | 2011-01-09 |
| George | 1998-05-18 |
| Wendell | 1982-09-24 |
| Bjorn | 2000-03-07 |
| Kristen | 1990-04-25 |
+———+————+

select name, birthdate from animals where species = ‘gorilla’ and name = ‘Max’

否定

QUERY = '''
select name, birthdate from animals where species != 'gorilla' and name != 'Max';
'''

between文

QUERY = '''
select name from animals where species = 'llama' AND birthdate between '1995-01-01' AND '1998-12-31';
'''

query

QUERY = "select max(name) from animals;"

QUERY = "select * from animals limit 10;"

QUERY = "select * from animals where species = 'orangutan' order by birthdate;"

QUERY = "select name from animals where species = 'orangutan' order by birthdate desc;"

QUERY = "select name, birthdate from animals order by name limit 10 offset 20;"

QUERY = "select species, min(birthdate) from animals group by species;"

QUERY = '''
 select name, count(*) as num from animals
 group by name
 order by num desc
 limit 5;
 '''

Limit count Offset skip
limit is how many rows to return
offset is how far into the results to start

Order by columns DESC
columns is which columns to sort by, separated with commas
DESC is sort in reverse order(descending)

Group by columns
columns is which columns to use as groupings when aggregating

QUERY = "select count(*) as num, species from animals group by species order by num desc;"

insert

INSERT_QUERY = '''
insert into animals (name, species, birthdate) values ('yoshi', 'opposum', '2016-12-13');
'''

php mysql で画像アップロード

%e7%84%a1%e9%a1%8c

<?php

/* html特殊文字をエスケープする関数 */
function h($str) {
  return htmlspecialchars($str, ENT_QUOTES, 'utf-8');
}

// xhtmlとしてブラウザに認識させる
//(ie8以下はサポート対象外)
header('Content-Type: application/xhtml+xml; charset=utf-8');

try {

  // データベースに接続
  $pdo = new PDO(
    'mysql:host=localhost;dbname=test;charset=utf8',
    'root',
    '',
    &#91;
      PDO::ATTR_EMULATE_PREPARES => false,
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]
  );

  /* アップロードがあったとき */
  if (isset($_FILES['upfile']['error']) && is_int($_FILES['upfile']['error'])){

    // バッファリングを開始
    ob_start();

    try {
      // $_FILES['upfile']['error']の値を確認
      switch ($_FILES['upfile']['error']){
        case UPLOAD_ERR_OK: // ok
          break;
        case UPLOAD_ERR_NO_FILE:
          throw new RuntimeException('ファイルが選択されていません', 400);
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
          throw new RuntimeException('ファイルサイズが大きすぎます', 400);
        default:
          throw new RuntimeException('その他のエラーが発生しました', 500);
      }

      // $_FILES['upfile']['mime']の値はブラウザ側で偽装可能なので
      // MIMEタイプを自前でチェックする
      if (!$info = getimagesize($_FILES['upfile']['tmp_name'])){
        throw new RuntimeException('有効な画像ファイルを指定してください', 400);
      }
      if (!in_array($info[2], [IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG], true)){
        throw new RuntimeException('未対応の画像形式です', 400);
      }

      // サムネイルをバッファに出力
      $create = str_replace('/', 'createfrom', $info['mime']);
      $output = str_replace('/', '', $info['mime']);
      if ($info[0] >= $inf0[1]){
        $dst_w = 120;
        $dst_h = ceil(120 * $info[1] / max($info[0], 1));
      } else {
        $dst_w = ceil(120 * $info[0] / max($info[1], 1));
        $dst_h = 120;
      }
      if (!$src = @$create($_FILES['upfile']['tmp_name'])){
        throw new RuntimeException('画像リソースの生成に失敗しました', 500);
      }
      $dst = imagecreatetruecolor($dst_w, $dst_h);
      imagecopyresampled($dst, $src, 0, 0, 0, 0, $dst_w, $dst_h, $info[0], $info[1]);
      $output($dst);
      imagedestroy($src);
      imagedestroy($dst);

      // INSERT処理
      $stmt = $pdo->prepare('INSERT INTO image(name,type,raw_data,thumb_data,date) VALUES(?,?,?,?,?)');
      $stmt->execute([
        $_FILES['upfile']['name'],
        $info[2],
        file_get_contents($_FILES['upfile']['tmp_name']),
        ob_get_clean(),
        (new DateTime('now', new DateTimeZone('Asia/Tokyo')))->format('Y-m-d H:i:s'),
      ]);

      $msgs[] = ['green', 'ファイルは正常にアップロードされました'];
    } catch (RuntimeException $e){

      while(ob_get_level()){
        ob_end_clean();
      }
      http_response_code($e instanceof PDOException ? 500 : $e->getCode());
      $msgs[] = ['red', $e->geteMessage()];

    }
  } elseif (isset($_GET['id'])){
    try {

      $stmt = $pdo->prepare('SELECT type, raw_data FROM iamge WHERE id = ? LIMIT 1');
      $stmt->bindValue(1, $_GET['id'], PDO::PARAM_INT);
      $stmt->execute();
      if (!$row = $stmt->fetch()){
        throw new RuntimeException('該当する画像は存在しません', 404);
      }
      header('X-Content-Type-Options: nosniff');
      header('Content-Type: ' . image_type_to_mime_type($row['type']));
      echo $row['raw_data'];
      exit;
    } catch (RuntimeException $e){

      http_response_code($e instanceof PDOException ? 500 : $e->getCode());
      $msgs[] = ['red', $e->getMessage()];
    }

  }

  $rows = $pdo->query('SELECT id,name,type,thumb_data,data From image ORDER BY date DESC')->fetchAll();

} catch(PDOException $e){
  http_response_code(500);
  $msgs[] = ['red', $e->getMessage()];
}
?>

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>画像アップロード</title>
    <style><!&#91;CDATA&#91;
    fieldset { margin: 10px; }
    legend { font-size: 12px; }
    img {
      border: none;
      float: left;
    }
    &#93;&#93;></style>
  </head>
  <body>
    <form enctype="multipart/form-data" method="post" action="">
      <fieldset>
        <legend>画像ファイルを選択(GIF, JPEG, PNGのみ対応)</legend>
        <input type="file" name="upfile" /><br>
        <input type="submit" value="送信" />
      </fieldset>
    </form>
  <?php if (!empty($msgs)): ?>
    <fieldset>
      <legend>メッセージ</legend>
  <?php foreach ($msgs as $msg): ?>
    <ul>
      <li style="color:<?=h($msg&#91;0&#93;)?>;"><?=h($msg&#91;1&#93;)?></li>
    </ul>
  <?php endforeach; ?>
</fieldset>
<?php endif; ?>
<?php if (!empty($rows)): ?>
  <fieldset>
    <legend>サムネイル一覧(クリックすると原寸大表示)</legend>
  <?php foreach ($rows as $i => $row): ?>
  <?php if ($i): ?>
    <hr />
  <?php endif; ?>
    <p>
      <?=sprintf(
        '<a href="?id=%d"><img src="data:%s;base64,%s" alt="%s" /></a>',
        $row['id'],
        image_type_to_mime_type($row['type']),
        base64_encode($row['thumb_data']),
        h($row['name'])
        )?><br>
        ファイル名: <?=h($row&#91;'name'&#93;)?><br />
        日付: <?=h($row&#91;'date'&#93;)?><br clear="all">
      </p>
    <?php endforeach; ?>
  </fieldset>
<?php endif; ?>
</body>
</html>

$_FILE

a

move_uploaded_file($_FILES[“upfile”][“tmp_name”], “files/” . $_FILES[“upfile”][“name”]で、画像をアップロード

form.html

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>sample</title>
</head>
<body>
  <form action="upload.php" method="post" enctype="multipart/form-data">
    ファイル:<br>
    <input type="file" name="upfile" size="30" /><br>
    <input type="submit" value="アップロード" />
  </form>
</body>
</html>

upload.php

<!DOCTYPE html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf8">
  <title>画像アップロード</title>
</head>
<body>
  <p><?php

  if (is_uploaded_file($_FILES&#91;"upfile"&#93;&#91;"tmp_name"&#93;)){
    if (move_uploaded_file($_FILES&#91;"upfile"&#93;&#91;"tmp_name"&#93;, "files/" . $_FILES&#91;"upfile"&#93;&#91;"name"&#93;)){
    chmod("files/" . $_FILES&#91;"upfile"&#93;&#91;"name"&#93;, 0644);
    echo $_FILES&#91;"upfile"&#93;&#91;"name"&#93; . "をアップロードしました。";
  } else {
    echo "ファイルをアップロードできません。";
  }
  } else {
    echo "ファイルが選択されていません。";
  }

   ?></p>
</body>
</html>

複数の画像を配列で保存

%e7%84%a1%e9%a1%8c

<?php
if (isset($_FILES&#91;'upfile'&#93;&#91;'error'&#93;) && is_int($_FILES&#91;'upfile'&#93;&#91;'error'&#93;)){

  // 各ファイルをチェック
  foreach ($_FILES&#91;'upfile'&#93;&#91;'error'&#93; as $k => $error){

  try {

    if (!is_int($error)){
      throw new RuntimeException("[{$k}] パラメータが不正です");
    }
    // $_FILES['upfile']['error']の値を確認
    switch ($_FILES['upfile']['error']){
      case UPLOAD_ERR_OK:
        break;
      case UPLOAD_ERR_NO_FILE:
        throw new RuntimeException('ファイルが選択されていません');
      case UPLOAD_ERR_INI_SIZE:
      case UPLOAD_ERR_FORM_SIZE: // フォーム定義の最大サイズ超過
        throw new RuntimeException('ファイルサイズが大きすぎます');
      default:
        throw new RuntimeException('その他のエラーが発生しました');
    }

    // $_FILES['upfile']['mime']の値はブラウザ側で偽装可能なので
    // MIMEタイプを自前でチェックする
    if (!$info @getimagesize($_FILES['upfile']['tmp_name'][$k])){
      throw new RuntimeException("[{$k}] 有効な画像ファイルを指定してください");
    }
    if (!in_array($info[2], [IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG], true)){
      throw new RuntimeException("[{$k}] 未対応の画像形式です");
    }

    // 画像処理に使う関数名を決定する
    $create = str_replace('/', 'createfrom', $info['mime']);
    $output = str_replace('/', '', $info['mime']);

    // 縦横比を維持したまま、120*120 以下に収まるサイズを求める
    if ($info[0] >= $info[1]){
      $dst_w = 120;
      $dst_h = ceil(120 * $info[1] / max($info[0], 1));
    } else {
      $dst_w = ceil(120 * $info[0] / max($info[1], 1));
      $dst_h = 120;
    }

    // 元画像リソースの生成を試みる
    if (!$src = @$create($_FILES['upfile']['tmp_name'][$k])){
      throw new RuntimeException("[{$k}] 画像リソースの生成に失敗しました");
    }

    // リサンプリング先画像リソースを生成する
    $dst = imagecreatetruecolor($dst_w, $dst_h);

    // getimagesize関数で得られた情報も利用してリサンプリングを行う
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $dst_w, $dst_h, $info[0], $info[1]);

    // ファイルデータからSHA-1ハッシュを取ってファイル名を決定し、保存する
    if (!$output(
      $dst,
      sprintf('./resized/%s%s',
        sha1_file($_FILES['upfile']['tmp_name'][$k]),
        image_type_to_extension($info[2])
        )
      )) {
        throw new RuntimeException("[{$k}] ファイル保存時にエラーが発生しました");
      }

    $msgs[] = ['green', "[{$k}] リサイズして保存しました"];
  } catch (RuntimeException $e){
    $msgs = ['red', $e->getMessage()];
  }

  if (isset($img) && is_resource($img)){
    imagedestroy($img);
  }
  if (isset($dst) && is_resource($dst)){
    imagedestroy($dst);
  }
}
}

// XTHMLとしてブラウザに認識させる
// (IE8以外はサポート対象外)
header('Content-Type: application/xhtml+xml; charset=utf-8');
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>画像アップロード</title>
</head>
<body>
<?php if (!empty($msgs)): ?>
  <ul>
<?php foreach ($msgs as $msg): ?>
    <li style="color:<?=$msg&#91;0&#93;?>;"><?=
    htmlspecialchars($msg&#91;1&#93;, ENT_QUOTES, 'UTF-8')
    ?></li>
<?php endforeach; ?>
  </ul>
<?php endif; ?>
  <form enctype="multipart/form-data" method="post" action="">
    <fieldset>
      <legend>画像ファイルを選択(GIF, JPEG, PNGのみ対応)</legend>
      <ul>
<?php for ($i = 0; $i < 10; $i++): ?>
      <li><input type="file" name="upfile&#91;&#93;" /></li>
<?php endfor; ?>
      </ul>
      <input type="submit" value="送信" />
    </fieldset>
  </form>
</body>
</html>

imagecreatefromstring

%e7%84%a1%e9%a1%8c
imagecreatefromstring
Create a new image from the image stream in the string

<?php
if (isset($_FILES&#91;'upfile'&#93;&#91;'error'&#93;) && is_int($_FILES&#91;'upfile'&#93;&#91;'error'&#93;)){
  try {
    // $_FILES&#91;'upfile'&#93;&#91;'error'&#93;の値を確認
    switch ($_FILES&#91;'upfile'&#93;&#91;'error'&#93;){
      case UPLOAD_ERR_OK:
        break;
      case UPLOAD_ERR_NO_FILE:
        throw new RuntimeException('ファイルが選択されていません');
      case UPLOAD_ERR_INI_SIZE:
      case UPLOAD_ERR_FORM_SIZE: // フォーム定義の最大サイズ超過
        throw new RuntimeException('ファイルサイズが大きすぎます');
      default:
        throw new RuntimeException('その他のエラーが発生しました');
    }

    // GD画像リソースの生成を試みる
    if (!$img = @imagecreatefromstring(file_get_contents($_FILES&#91;'upfile'&#93;&#91;'tmp_name'&#93;))){
      throw new RuntimeException('有効な画像ファイルを指定してください');
    }

    // ファイルデータからSHA-1ハッシュを取ってファイル名を決定し、保存する
    if (!imagepng($img, sprintf('./uploads/%s.png', sha1_file($_FILES&#91;'upfile'&#93;&#91;'tmp_name'&#93;)))){
      throw new RuntimeException('ファイル保存時にエラーが発生しました');
    }
    $msg = &#91;'green', 'ファイルは正常にアップロードされました'&#93;;
  } catch (RuntimeException $e){
    $msg = &#91;'red', $e->getMessage()];
  }

  if (isset($img) && is_resource($img)){
    imagedestroy($img);
  }
}

// XTHMLとしてブラウザに認識させる
// (IE8以外はサポート対象外)
header('Content-Type: application/xhtml+xml; charset=utf-8');
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>画像アップロード</title>
</head>
<body>
<?php if (isset($msg)): ?>
  <fieldset>
    <legend>結果</legend>
    <span style="color:<?=$msg&#91;0&#93;?>;"><?=$msg&#91;1&#93;?></span>
  </fieldset>
<?php endif; ?>
  <form enctype="multipart/form-data" method="post" action="">
    <fieldset>
      <legend>画像ファイルを選択</legend>
      <input type="file" name="upfile" /><br />
      <input type="submit" value="送信" />
    </fieldset>
  </form>
</body>
</html>

exif_imagetype

is_int
Find whether the type of a variable is integer

$_FILES[”][‘error’]
PHP returns an appropriate error code along with the file array. The error code can be found in the error segment of the file array that is created during the file upload by PHP.
UPLOAD_ERR_OK, UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE, UPLOAD_ERR_PARTIAL, UPLOAD_ERR_NO_FILE, UPLOAD_ERR_NO_TMP_DIR, UPLOAD_ERR_CANT_WRITE, UPLOAD_ERR_EXTENSION

exif_imagetype
Determine the type of an image
IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG

sprintf
Return a formatted string

image_type_to_extension
Get file extension for image type

<?php
if (isset($_FILES&#91;'upfile'&#93;&#91;'error'&#93;) && is_int($_FILES&#91;'upfile'&#93;&#91;'error'&#93;)){
  try {
    // $_FILES&#91;'upfile'&#93;&#91;'error'&#93;の値を確認
    switch ($_FILES&#91;'upfile'&#93;&#91;'error'&#93;){
      case UPLOAD_ERR_OK:
        break;
      case UPLOAD_ERR_NO_FILE:
        throw new RuntimeException('ファイルが選択されていません');
      case UPLOAD_ERR_INI_SIZE:
      case UPLOAD_ERR_FORM_SIZE: // フォーム定義の最大サイズ超過
        throw new RuntimeException('ファイルサイズが大きすぎます');
      default:
        throw new RuntimeException('その他のエラーが発生しました');
    }

    // $_FILES&#91;'upfile'&#93;&#91;'mime'&#93;の値はブラウザ側で偽装可能なので、MIMEタイプを自前でチェック
    $type = @exif_imagetype($_FILES&#91;'upfile'&#93;&#91;'tmp_name'&#93;);
    if(!in_array($type, &#91;IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG&#93;, true)) {
      throw new RuntimeException('画像形式が未対応です');
    }

    // ファイルデータからSHA-1ハッシュを取ってファイル名を決定し、ファイルを保存する
    $path = sprintf('./img/%s%s', sha1_file($_FILES&#91;'upfile'&#93;&#91;'tmp_name'&#93;), image_type_to_extension($type));
    if (!move_uploaded_file($_FILES&#91;'upfile'&#93;&#91;'tmp_name'&#93;, $path)){
      throw new RuntimeException('ファイル保存時にエラーが発生しました');
    }
    chmod($path, 0644);

    $msg = &#91;'green', 'ファイルは正常にアップロードされました'&#93;;
  } catch (RuntimeException $e){
    $msg = &#91;'red', $e->getMessage()];
  }
}

// XTHMLとしてブラウザに認識させる
// (IE8以外はサポート対象外)
header('Content-Type: application/xhtml+xml; charset=utf-8');
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>画像アップロード</title>
</head>
<body>
<?php if (isset($msg)): ?>
  <fieldset>
    <legend>結果</legend>
    <span style="color:<?=$msg&#91;0&#93;?>;"><?=$msg&#91;1&#93;?></span>
  </fieldset>
<?php endif; ?>
  <form enctype="multipart/form-data" method="post" action="">
    <fieldset>
      <legend>画像ファイルを選択(GIF, JPEG, PNGのみ対応)</legend>
      <input type="file" name="upfile" /><br />
      <input type="submit" value="送信" />
    </fieldset>
  </form>
</body>
</html>