PHP实例-编写自己的PHP通讯录4-添加联系人

通过清心醉

PHP实例-编写自己的PHP通讯录4-添加联系人

添加联系人的话,其实就是插入MYSQL数据,相对来说还是容易理解的.

只是在添加的时候,唯一的ID值必须+1,才能确保不会重复,这样对后续的修改和删除会有帮助.比较容易管理.

<?php
header(“Content-Type:text/html;charset=utf-8”);
//增加联系人表单
require_once(“inc.config.php”); //增加验证.防止恶意文件访问增加数据
?>
<html>
<title>添加联系人</title>
<body>
<form method=”post” action=”increasesql.php”>
<table width=”400″ align=”center”>
<tr>
<td>联系人名字(NAME):</td>
<td><input name=”contactsname” type=”text” size=”30″ maxlength=”500″></td>
</tr>
<tr>
<td>联系人性别(SEX):</td>
<td><input name=”contactssex” type=”radio” size=”30″ maxlength=”30″ value=”男”>男
<input name=”contactssex” type=”radio” size=”30″ maxlength=”30″ value=”男”>女</td></td>
</tr>
<tr>
<td>联系人电话(PHONE):</td>
<td><input name=”contactsphone” type=”text” size=”30″ maxlength=”500″></td>
</tr>
<tr>
<td>联系人地址(ADDRESS):</td>
<td><input name=”contactsaddress” type=”text” size=”30″ maxlength=”500″></td>
</tr>
</table>
<div align=”center”><input type=”submit” value=”添加”></div>
</form>
</body>
</html>

#因为ID不能由用户自己设置,所以在SQL执行的位置对ID进行特别处理,具体请看:

<?php
header(“Content-Type:text/html;charset=utf-8”);
//增加联系人SQL操作.
require_once(“inc.config.php”); //验证身份
require_once (“config.php”);//获取数据库信息
$contactsname= @$_POST[“contactsname”];
$contactssex= @$_POST[“contactssex”];
$contactsphone= @$_POST[“contactsphone”];
$contactsaddress= @$_POST[“contactsaddress”];
if (is_array($_POST)&&count($_POST)>0)
{
if(!empty($_POST[“contactsname”])&&!empty($_POST[“contactssex”])&&!empty($_POST[“contactsphone”])&&!empty($_POST[“contactsaddress”]))
//!empty比isset好的就是,isset是判断是否存在,!empty是判断是否为空值
{
if(!eregi(“^[0-9]+$”,$contactsphone)) //判断是否非数字
{
echo “电话号码非数字”;
echo “<script>setTimeout(\”this.location=’index.php’\”,2000);</script>”;
exit;
}
$contacts = mysql_query(“select max(id) sqlmaxid from contacts”);
//定义一个查询contacts表,列为id的变量,输入的名字为sqlmaxid;
while($sqlmaxid = mysql_fetch_object($contacts)) //循环读取
$tempmaxid = $sqlmaxid->sqlmaxid;
//定义临时变量,参数=while循环变量的sqlmaxid指向sql语句中的max(id),命名为sqlmaxid(第10行的sql语句中)
$insqlmaxid=$tempmaxid+1;
//定义写入SQL的id,值=while循环提出出来的最大id值+1;
$increasesql=”INSERT INTO contacts(id,names,sex,phone,address) VALUES(‘$insqlmaxid’,’$contactsname’,’$contactssex’,’$contactsphone’,’$contactsaddress’)”;
mysql_query($increasesql,$con);//插入$_POST的数据和+1的id参数到数据库
mysql_close($con); //关闭MYSQL
echo “添加联系人成功</br>”;
echo “正在返回首页,请稍后…”;
echo “<script>setTimeout(\”this.location=’index.php’\”,2000);</script>”;
}
else
{
echo “请完整填写数据!”;
echo “<script>setTimeout(\”this.location=’index.php’\”,2000);</script>”;
}
}
else
{
echo “非法访问”;
}
?>

#从这代码应该可以看出来,通过while循环读取contacts表里的id列,max是最大的意思,然后由于读出后,要给他命名,作者命名为sqlmaxid.

 

 

关于作者

清心醉 administrator

发表评论

如果喜欢作者的文章,您可以打赏给作者:

TRC20(虚拟货币):


ERC20(虚拟货币):


Bitcoin(BTC):