Skip to content

Instantly share code, notes, and snippets.

@KimiyukiYamauchi
Created December 20, 2013 12:04
Show Gist options
  • Select an option

  • Save KimiyukiYamauchi/8053845 to your computer and use it in GitHub Desktop.

Select an option

Save KimiyukiYamauchi/8053845 to your computer and use it in GitHub Desktop.
<?php
// 日本語の文字コード設定などを予め定義
mb_internal_encoding("UTF-8");
mb_language("ja");
setlocale(LC_ALL,"ja_JP.UTF-8");
// csv
$bbs_file = "bbs.csv";
// エスケープを行うラップ関数を定義
function h($str) {
return htmlspecialchars($str, ENT_QUOTES, "UTF-8");
}
// 掲示板のデータをファイルに書き込む関数を定義
function bbs_write($data)
{
$dsn = 'mysql:dbname=testphp;host=localhost';
$user = 'test';
$password = 'pass';
try{
$db = new PDO( $dsn, $user, $password);
// echo "接続に成功しました\n<br />";
$db->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$stmt = $db->query('select post_id from bbs order by post_id desc limit 1');
$result = $stmt->fetchColumn();
if($result && !is_null($result)){
$post_id = $result + 1;
}else{
$post_id = 1;
}
// コメントの改行コードを統一する
$data["comment"] = str_replace(
array("\r\n", "\n", "\r"),
PHP_EOL, $data["comment"]);
// Insert the new dish into the table
$sth = $db->prepare('INSERT INTO bbs (post_id, name, comment, time) VALUES (?,?,?,?)');
$sth->execute(array($post_id, $data["name"], $data["comment"], date('y/m/d H:i:s')));
} catch (PDOException $e){
echo "失敗しました\n";
var_dump($e->getMessage());
return false;
}
return true;
}
// 掲示板のデータをファイルから読み込む関数を定義
function bbs_read()
{
$dsn = 'mysql:dbname=testphp;host=localhost';
$user = 'test';
$password = 'pass';
try{
$db = new PDO( $dsn, $user, $password);
// echo "接続に成功しました\n<br />";
$db->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
// build up the query
$sql = 'select name,comment,time ' .
'from bbs order by post_id desc';
// Send the query to the database program and get all the rows back
$sth = $db->prepare($sql);
$sth->execute();
$ret = $sth->setFetchMode(PDO::FETCH_OBJ);
$posts = $sth->fetchAll();
if (count($posts) == 0) {
print 'No dishes matched.';
} else {
foreach ($posts as $post) {
$record["name"] = $post->name;
$record["comment"] = $post->comment;
$record["time"] = strtotime($post->time);
$records[] = $record;
}
}
} catch (PDOException $e){
echo "失敗しました\n";
var_dump($e->getMessage());
}
// 関数の実行結果を返す
return $records;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment