php-表单数据保存至阿里云ECS mysql(笔记)
准备工作:
1在阿里云phpmyadmin中添加账号,允许%主机连接(所有ip),或者添加一个localhost账号
2写好表单数据,使用php传值
代码如下:
<?php
$kc_arr = array();
$kc_arr = $_POST['chk'];
$kc = implode(", ", $kc_arr);
$con = mysql_connect("localhost","admin","pw");
mysql_select_db("wl_student",$con);
$sql="INSERT INTO bm_student(sname,phone,kc,sj)
VALUES
('$_POST[sname]','$_POST[phone]','$kc',NOW())";
$res = mysql_query($sql, $con);
$err = mysql_error();
if($err){
echo "发生错误,请通知管理员";
}
$row = mysql_fetch_row($res);
echo " ";
mysql_close($con)
?>
使用implode将数组类型转为字符串,保存至mysql中。
表单页面:(防止跳转php新页面,并进行表单验证)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<title>name</title>
<style>
button, input, select, textarea {
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
element.style {
display: inline-block;
border: 3px outset rgb(251, 205, 15);
border-radius: 10px;
background-color: white;
padding-left: 4px;
padding-right: 4px;
width: 100%;
color: rgb(52, 54, 60);
font-size: 120%;
text-align: left;
box-shadow: rgb(45, 66, 87) 0px 0px 3px inset;
}
</style>
<script type="text/javascript">
function btnck(){
var a=document.getElementById("sname");
var b=document.getElementById("btn");
var c=document.getElementById("phone");
if(a.value==""||c.value.length!==11){
alert("带*信息填写错误!");
return false;
}
else{
alert("提交成功!");
return true;
}
}
</script>
</head>
<div align="center">
<div style="width:100%; height:100%">
</div>
<form action="insert-2.php" method="post" target="nm_iframe"><br />
<p>*<input type="text" name="sname" id="sname" placeholder="请输入姓名"/></p><br />
<p>*<input type="text" name="phone" id="phone" placeholder="请输入联系方式"/></p>
<p><p><br />
<!--<p>时间 <input type="text" name="time" /></p><br />-->
<input type="checkbox" name="chk[]" value="1"/>1
<input type="checkbox" name="chk[]" value="2"/>2<br /><br />
<input type="checkbox" name="chk[]" value="3"/>3
<input type="checkbox" name="chk[]" value="4"/>4<br /><br />
<input type="checkbox" name="chk[]" value="5"/>5
<br /><br /><br />
<input type="submit" id="btn" onclick="btnck();" value="点击提交"/><br /><br />
</form>
</div><iframe id="id_iframe" name="nm_iframe" style="display:none;"></iframe>
</body>
</html>
参考连接: