新卒から文系エンジニア→人材業界に転職した人のブログ

新卒から文系エンジニア→人材業界に転職。技術・スキルがないためブログを通して勉強。その後、IT業界の業界知識が活かせる人材業界へ。異業種×異職種の転職経験有り。

このエントリーをはてなブックマークに追加

【php・mysql・xmlhttprequest】DBへの登録・変更・検索・削除 ~レコードの登録~

【今回の紹介】


前回まででmysqlをインストールし、DBの接続を確認するこ
とまで完了しました。



今後は、DBを使用した以下の基本的な操作を行っていきたいと思います。

・登録
・検索
・変更
・削除


ちなみに今回は、登録処理です。

【処理の流れ】

 ■登録

  ①画面から入力した値を登録(画面遷移なし)

  1、画面から入力した値を取得

  2、phpに取得した値を渡す

  3、phpにてDBに接続

  4、クエリの実行(取得した値をセット)

  5、結果の出力

  js→xmlhttprequestobj→php

  ※phpにて、db接続・クエリのセット・実行を行う


【参考ソース】

入力画面

<?php
$mysqli=new mysqli('localhost','sa','qwertyuiop@1','test_db');
if($mysqli->connect_error){echo "DB接続できませーん";}
$stmt=$mysqli->prepare("SET NAMES utf8");
$stmt->execute();
$stmt=$mysqli->prepare("select * from test_table") or exit("error");
$stmt->execute();
$stmt->bind_result($result_id,$result_name);
?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
name:<input type="text" id="text_1">
<input type="button" id="button_1" onclick="send_db()" value="登録"></br>
<table border="1">
<?php
while($stmt->fetch()){
echo '<tr>';
echo '<td>'.$result_id.'</td>';
echo '<td>'.$result_name.'</td>';
echo '</tr>';
}
?>
</table>
<?php
echo <<<EOM
<script type="text/javascript">
function send_db(){
		<!--text.idを設定-->
		var send_text=encodeURIComponent(document.getElementById("text_1").value);
		var url="send_db.php";
		var httpobj =createHttpRequest();
		httpobj.onreadystatechange = function() {
  			if (httpobj.readyState == 4) {
    			alert(httpobj.statusText);
  			}
			};
		httpobj.open("POST",url);
		httpobj.setRequestHeader('Pragma', 'no-cache');
  	    httpobj.setRequestHeader('Cache-Control', 'no-cache');
  		httpobj.setRequestHeader('If-Modified-Since', 'Thu, 01 Jun 1970 00:00:00 GMT');
		httpobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		httpobj.send("send_value="+send_text);
	}


<!--xmlhttprequestobjの生成-->
function createHttpRequest(){
	try{
			return new XMLHttpRequest();
		}catch(e){}
		try{
			return new ActiveXObject('MSXML2.XMLHTTP.6.0');
		}catch(e){}
		try{
			return new ActiveXObject('MSXML2.XMLHTTP.3.0');
		}catch(e){}
		try{
			return new ActiveXObject('MSXML2.XMLHTTP');
		}catch(e){}
	
		return null;
	}
	

	
</script>
EOM
?>
</body>
</html>

処理画面(とりあえず、IDは100にしてあります。)

<?php
  header('Content-Type: text/html; charset=UTF-8');
    $input=$_POST['send_value'];
    $mysqli=new mysqli('localhost','sa','qwertyuiop@1','test_db');
		if($mysqli->connect_error){echo "DB接続できませーん";}
	$stmt=$mysqli->prepare("SET NAMES utf8");
	$stmt->execute();
	$stmt=$mysqli->prepare("insert into test_table values(100,'$input')") or exit("error");
	$stmt->execute();
?>
.hatena-module:nth-of-type(10) { background: transparent; } .hatena-module:nth-of-type(10) .hatena-module-title{ display: none; } .hatena-module:nth-of-type(10) .hatena-module-body { padding: 0; }