標籤:串連資料庫 使用者名稱 action 密碼 ajax
如果要跳轉頁面,那麼form上要定義action跳轉到相關頁面,同時提交按鈕的type要為submit,如下:
<
form
action
=
"test2.php"
method
=
"post"
>
<input type="submit" value="提交" />
不跳轉用ajax重新整理的代碼如下:
html代碼:
<body>
<div align="center">
<form id="form1" name="form1" method="post" action="test2.php">
<table width="500" border="1" cellspacing="0" cellpadding="5">
<tr>
<td colspan="2" align="center" bgcolor="#CCCCCC"><strong>使用者註冊</strong></td>
</tr>
<tr>
<td width="101" align="right">使用者名稱:</td>
<td width="393" align="left"><label>
<input type="text" name="username" />
</label></td>
</tr>
<tr>
<td align="right">密碼:</td>
<td align="left"><label>
<input type="text" name="password" />
</label></td>
</tr>
<tr>
<td align="right"> </td>
<td align="left"><label>
<input type="submit" name="Submit" value="提交" />
<input type="reset" name="Submit2" value="重設" />
</label></td>
</tr>
</table>
</form>
</div>
<br /><br />
<div id="d1" style="font-size:35px; text-align:center;"> </div>
</body>
JS代碼:
<script language="javascript">
function f1()
{
//建立xmlHttp對象
var xmlHttp;
if(window.ActiveXObject)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();
}
//擷取表單值
var username=document.form1.username.value;
var password=document.form1.password.value;
var datastr="username="+username+"&password="+password;
var url="/test2.php";
//提交資料
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4&&xmlHttp.status==200){
document.getElementById("d1").innerHTML=xmlHttp.responseText;
}
}
xmlHttp.open("POST",url,true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send(datastr);
}
</script>
PHP代碼:
<?php
$conn = mysql_connect(‘localhost‘,‘root‘,‘‘);
mysql_query("set names utf-8");
mysql_select_db( "test" );
function inject_check($sql_str){
return preg_match("/select|insert|update|delete|\‘|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile|%|eval|=|and|‘|;|exec|count/i", $sql_str); // 進行過濾
}
if(!empty($_POST)){
foreach($_POST as $key => $value){
if(inject_check($value)){
exit (‘<script>alert("地址欄輸入發現有非法字元,請重新輸入!");history.go(-1);</script>‘);
die ();
}
}
}
//這裡的變數名改成相應的變數名
$res = mysql_query("SELECT count(*) as m from `user` where username=‘${_POST[‘username‘]}‘ AND password=‘${_POST[‘password‘]}‘");
$row = mysql_fetch_object($res);
if($row->m >0){
echo "登陸成功";
}else{
echo "登陸失敗";
}
exit;
?>
php 串連資料庫 驗證使用者名稱密碼