【php・mysql・xmlhttprequest】DBへの登録・変更・検索・削除 ~レコードの変更~
【処理の流れ】
【変更処理】
1、画面から入力した値を取得(変更したいidを入力)
2、phpに取得した値を渡す
3、phpにてDBに接続
4、クエリの実行(取得した値をセット)→update文
5、結果の出力
【参考ソース】
<?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> id:<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_text1=encodeURIComponent(document.getElementById("text_1").value); var url="update_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_text1); } <!--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>
変更処理
<?php header('Content-Type: text/html; charset=UTF-8'); $input=$_POST['send_value']; //var $input1=explode(",",$input); $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("update test_table set name='変更' where id='$input' ") or exit("error"); $stmt->execute(); ?>