SSブログ

書籍データをDBに登録 [php]

バーコードリーダーで読み込んだISBNを基に情報をDBに登録していきます。


<?php
//準備
ini_set('display_errors', "On");
error_reporting(E_ALL);

$id = 0;
//接続用
$USER = 'USER';
$PW ='PASS';
$dnsinfo = "mysql:dbname=DBNAME;host=localhost;charset=utf8";


//入力が確認された場合に処理を実行
if(isset($_POST["ISBN"])){
	$ISBN = $_POST["ISBN"];
	$data = "https://api.openbd.jp/v1/get?isbn={$ISBN}";
	$json = file_get_contents($data);
	$json_decode = json_decode($json,true);

//変数へ格納
	$BookTitle = $json_decode[0]['summary']['title'];
	$author = $json_decode[0]['summary']['author'];
	$publisher = $json_decode[0]['summary']['publisher'];
	$pubdate = $json_decode[0]['summary']['pubdate'];
	$CoverUrl = $json_decode[0]['summary']['cover'];

if ($BookTitle == "") {
	echo "情報を取得できませんでした。\nデータを追加できません。";
	$recordlist ="";
}else {
//データベースへの接続及び追加
	try {
	  $pdo = new PDO($dnsinfo,$USER,$PW);
		$sql = "INSERT INTO details VALUES(?,?,?,?,?,?)";
	  $stmt = $pdo->prepare($sql);
	  $array = array($id,$BookTitle,$author,$publisher,$pubdate,$CoverUrl);
	  $res = $stmt->execute($array);

	} catch (Exception $e) {
	  $res = $e->getMssage();
	}
}



if ($CoverUrl == "") {
	$CoverUrl = "書影が見つかりませんでした";
}

//表示するものども
	$table =  "<table border='1'>";
	$table .= "<tr><th colspan='2'>書籍情報</th></tr>";
	$table .= "<tr><td colspan='2'><img src='{$CoverUrl}'></td></tr>";
	$table .= "<tr><td>タイトル</td><td>{$BookTitle}</td></tr>";
	$table .= "<tr><td>著者</td><td>{$author}</td></tr>";
	$table .= "<tr><td>出版社</td><td>{$publisher}</td></tr>";
	$table .= "<tr><td>出版年</td><td>{$pubdate}</td></tr>";
	$table .= "</table>";

}else {
	$result = "";
	$table = "";
	$recordlist ="";
}
$pdo2 = new PDO($dnsinfo,$USER,$PW);
$sql2 ="SELECT *FROM details";
$stmt2 = $pdo2->prepare($sql2);
$stmt2->execute(null);
$recordlist = "<table border='2'><th>ID</th><th>題名</th><th>著者</th><th>出版社</th><th>出版年</th>\n";
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC)) {
	$recordlist .= "<tr><td>{$row['id']}</td>";
	$recordlist .= "<td>{$row['title']}</td>";
	$recordlist .= "<td>{$row['author']}</td>";
	$recordlist .= "<td>{$row['publisher']}</td>";
	$recordlist .= "<td>{$row['pubdate']}</td></tr>";
}
$recordlist .= "</table>\n";
?>
<!DOCTYPE html>
<html lang="ja">
	<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" href="style.css">
	<title>書籍管理システム</title>
	<script>document.book_info.ISBN.focus();</script>
	</head>
<body>
	<nav>
		<div class="logo">
			<h1><a href="./index.php"> 書籍管理<簡易></a></h1>
		</div>

	</nav>
	<h1>書籍追加</h1>
	<form action="" method="post">
		<b>ISBNを入力:<input type="textarea" name="ISBN" id=book_info autofocus></b>
		<input type="submit" name="submit">
	</form>
	<?php echo $result;?>
	<?php echo $table;?>
	<button name='regist'>登録</button>
	<h1>データ一覧</h1>
	<?php echo $recordlist;?>
</body>
</html>



nice!(0)  コメント(0) 

データベース設定

MySQLでデータベースを作りましょう。
データベース名は適当に作ってください。

CREATE DATABASE tekito;


テーブルはしっかりと。
IDに関してはあった方が良いかと思って付けましたが、使うだろうか…。
ちなみに追加されるごとに自動で連番になるような設定になります。AUTOなんたら、といった部分がそうですね。
create table details(
id INT AUTO_INCREMENT PRIMARYKEY,
title VARCHAR(200),
author VARCHAR(80),
publisher VARCHAR(50),
pubdate VARCHAR(30),
cover VARCHAR(200),
)



nice!(0)  コメント(0) 

有線LANで繋いでいるWin10のPCをアクセスポイント化

ここで思い出した小技を一つ…。
Win10の機能として現在のネットワークを使ってWi-fiを飛ばすことが出来るというものがあります。
スタートメニューから【設定】を開き、【ネットワーク】を選択。
【モバイルホットスポット】をクリックすると「インターネット接続を他のデバイスと共有します」という文があるかと思います。
そこのトグルをぽちっとクリックしてもらうとあら不思議。
その下に記載されているネットワーク名とパスワードで新しいWi-fiのアクセスポイントが出来ているではありませんかー。

これWin7だと面倒だったので結構助かったりしています。
nice!(0)  コメント(0) 

書影を登録

openbdさんが気前よく書影を取得できるようにしてくださっているので、これを活用しましょう。
個人的にはpythonでやりたいのですが、今回はPHPとMySQLでのWebアプリなので、PHPでやっていきます。
実際に走らせる際はimg src=""としてくださいね。
ISBNをURLの末尾にくっつけてやればJSONで帰ってくるので、必要な情報だけ取得して変数に入れてやりましょう。

$ISBN = "4480020470";
$data = "https://api.openbd.jp/v1/get?isbn={$ISBN}";
$json = file_get_contents($data);
$json_decode = json_decode($json,true);

//各種情報の取得
$BookTitle = $json_decode[0]['summary']['title'];
$author = $json_decode[0]['summary']['author'];
$publisher = $json_decode[0]['summary']['publisher'];
$pubdate = $json_decode[0]['summary']['pubdate'];
$CoverUrl = $json_decode[0]['summary']['cover'];
echo "< i mg src={$CoverUrl}>";

nice!(0)  コメント(0) 

GUI その2

GUI作成その2
ラジオボタン
ラジオボタンを作成してオモシロイアプリを作ってみました。

import tkinter as tk

def get_radiobutton():
    # この先の人生を判定
    # ラジオボタンから送られてきた値を取得して処理
    if intvar.get() == 0:
        print("あなたはとても良い人生を送るでしょう。")
    else:
        print("あなたはこの先の人生、とても苦労することでしょう。おかわいそうに…。")
root = tk.Tk()
root.geometry("400x400")
root.title("RadioButton")
intvar = tk.IntVar()

intvar.set(0)
# ラベルを作成
q1_lb = tk.Label(text="あなたが好きなのはたけのこの里、それともきのこの山(笑)?")
# ラジオボタン作成
rd1 = tk.Radiobutton(text="たけのこの里", value="0", variable=intvar)
rd2 = tk.Radiobutton(text="きのこの山(笑)", value="1", variable=intvar)
# 確定ボタンとその処理を記載
bt_submit = tk.Button(text="確定", command=get_radiobutton)

[widget.pack() for widget in (q1_lb,rd1, rd2,bt_submit)]
root.mainloop()


nice!(0)  コメント(0) 

phpでDB接続 [php]

csvとかで管理して表示とかでもできるのかもしれませんが、やっぱりデータベース使うと格好いい(小並感)
そんなわけで


「」で囲まれた部分は各自変えるべし。
ini_set('display_errors', "On");
error_reporting(E_ALL);

class DB{
  private $USER = '「USER_NAME」';
  private $PW = '「PASSWORD」';
  private $dnsinfo = "mysql:dbname=「DBNAME」;host=localhost;charset=utf8";

  private function Connectdb(){
    try{
      $pdo = new PDO($this->dnsinfo,$this->USER,$this->PW);
      return $pdo;
    }catch(Exception $e){
      return false;
    }
  }

    public function executeSQL($sql,$array){
      try{
        if(!$pdo = $this->Connectdb())return false;
        $stmt = $pdo->prepare($sql);
        $stmt->execute($array);
        return $stmt;

      }catch(Exception $e){
        return false;
      }
    }
}
 ?>

nice!(0)  コメント(0) 

書籍管理 [php]

私の蔵書が100冊を超えてきたので整理するためにバーコードリーダーを買いましたー。
こんな感じのやつ。





こいつを使って書籍管理をしていきたいと思います。
構成としてはphpで登録ページを作ってバーコードリーダーで読み込むとISBNから書籍情報を検索してタイトル、著者名、出版社、出版年を取得。書影とともにデータベースに保存。といった形です。
そしてトップページには書籍をずらっと一覧表示していきます。

ではそのコードは次の記事で。
nice!(0)  コメント(0) 

GUIアプリを作りたい [python]

pythonでGUI系を作るものとして最も有名?なのがtkinter。
他にも色々ありそうですが、メジャーで情報が多そうなのでこちらを採用。

ラベルの表示とボタンの表示と機能の作成。
テキストボックスとその内容の表示を試してみた。
今日はとりあえずここまで。

import tkinter as tk
root = tk.Tk()
#タイトル名の指定
root.title("タイトル")
#画面サイズの指定
root.geometry("450x350")

def button_action():
    print('キサマッッ!!今ッッ!!そのボタンを押したなッッ!!!')
def print_text():
    val_text = txtbox.get()
    print(val_text)

#ボタン、ラベルの設定
lb = tk.Label(text="ラベル")
bt = tk.Button(text="ボタン", command=button_action)
#テキストボックスの作成
txtbox = tk.Entry()
txtbutton = tk.Button(text="送信", command=print_text)

#ボタン、ラベルの表示
lb.pack()
bt.pack()
[widget.pack() for widget in (lb, txtbox, txtbutton)]

root.mainloop()


nice!(0)  コメント(0) 

vimに暗黒の力を

暗黒vim王ことShougoさんのお創りになられたdein.vimをインストールします。
vimのプラグインの管理用ソフトですね。
まずはDeinをインストールするディレクトリを作成し、移動します。
mkdir -p ~/.cache/dein 
cd ~/.cache/dein


curl https://raw.githubusercontent.com/Shougo/dein.vim/master/bin/installer.sh > installer.sh
sh ./installer.sh ~/.cache/dein


これが終わると以下のような表示がされるはず。
///////////////////////////////////////////////////////////////////////////////////////////////////
git は /usr/bin/git です

Begin fetching dein...
Cloning into '/home/tender/.cache/dein/repos/github.com/Shougo/dein.vim'...
remote: Enumerating objects: 60, done.
remote: Counting objects: 100% (60/60), done.
remote: Compressing objects: 100% (51/51), done.
remote: Total 60 (delta 1), reused 23 (delta 0), pack-reused 0
Unpacking objects: 100% (60/60), done.
Done.

Please add the following settings for dein to the top of your vimrc (Vim) or init.vim (NeoVim) file:


"dein Scripts-----------------------------
if &compatible
set nocompatible " Be iMproved
endif

" Required:
set runtimepath+=/home/tender/.cache/dein/repos/github.com/Shougo/dein.vim

" Required:
call dein#begin('/home/tender/.cache/dein')

" Let dein manage dein
" Required:
call dein#add('/home/tender/.cache/dein/repos/github.com/Shougo/dein.vim')

" Add or remove your plugins here like this:
"call dein#add('Shougo/neosnippet.vim')
"call dein#add('Shougo/neosnippet-snippets')

" Required:
call dein#end()

" Required:
filetype plugin indent on
syntax enable

" If you want to install not installed plugins on startup.
"if dein#check_install()
" call dein#install()
"endif

"End dein Scripts-------------------------


Done.
Complete setup dein!
///////////////////////////////////////////////////////////////////////////////////////////////////

この "dein Scripts----------------------------- から "End dein Scripts-------------------------までをコピーして
ホームディレクトリの「.vimrc」に追記します。

完成!
nice!(0)  コメント(0) 

単語帳をつくろう

pythonでは多層配列を辞書型と呼んでいます。
そんな辞書型を使って単語帳を作っていくこととします。
そんな訳でほい。

import random
from time import sleep
ejdic ={}
f = open('eiwa.csv')

for i in f:
    x = f.readline()
    tmp_list = x.split(',') #カンマ区切りを分けてリストへIN!!!!
    eng = tmp_list[0]#.upper()
    ja = tmp_list[1]
    ejdic[eng]=ja
    englishes = random.choice(list(ejdic))
    englishes = englishes
    print(englishes)
    print('↓')
    sleep(3)
    print(ja)


eiwa.csvという形で英語、日本語という形でカンマ区切りのファイルを作成していることが前提となります。
これでtkinterとか使ってデスクトップアプリにできたらいいなー。
nice!(0)  コメント(0) 

この広告は前回の更新から一定期間経過したブログに表示されています。更新すると自動で解除されます。