0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

データベースに保存 session75

Posted at

入力して配列に一時保存している会員情報をデータベースに保存するプログラムを作成する。

まずはデータベースにアクセスするプログラムを作成していく。

データベースにアクセスするプログラムは何度も使用するので別ファイルに書いてインクルード(呼び出す)する形を取る。

同じフォルダ内にファイルを作成していく。
dbconnect.phpを作成する。

try{
try{
    $db = new PDO('mysql:dbname=mini_bbs;host=127.0.0.1;charset=stf8','root','root')
}

まずは例外処理というものをやっていく

mini_bbsの部分は phpMyAdminで作った今回使用するDBの名称になる
host後のIPアドレスはローカルアドレスを指定
文字はutf8を指定
ユーザー名とパスワードはMAMPの場合、それぞれ root になる(XAMPPの場合、パスワードは’’ ←なし)

これでDBに接続できるようになる。

今回作成した dbconnect.php をcheck.php の会員登録のデータベースに登録していく


<?php
session_start();
require('../dbconnect.php');

if(!isset($_SESSION['join'])){
	header('Location: index.php');
	exit();
}

//登録ボタンが押されたら、データベースに情報を保存する
if(!empty($_POST)){
	$statement = $db->prepare('INSERT INTO members SET name=?, email=?, password=?, picture=?, created=NOW()');
	echo $statement -> execute(array(
		$_SESSION['join']['name'],
		$_SESSION['join']['email'],
		sha1($_SESSION['join']['password']),
	));
	unset($_SESSION['join']);

	header('Location: thanks.php');
	exit();
}

?>

check.phpの先頭部分にrequire('../dbconnect.php');を追加する。

prepareで準備した ? に値を入れていく。
echo 以降の記述で値を入れていく。

unsetは SESSION変数を空にする命令になる。
→上記の記述でデータベースに値を保存したのでSESSION変数に値を保存しておく
意味がなくなったので初期化しておく。
保存し終わったSESSION変数に値が残っているとデータベースのデータと重複してしまう
可能性があるのでそれを防いでおく。

データベースに保存し、SESSION変数の値を空にしたら、
header('Location: thanks.php'); exit();でthanks.phpに移動して処理を終了させる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?