小言_互联网的博客

Mac搭建 php 网页操作本地 mysql 数据库2 —— 添加数据

203人阅读  评论(0)

添加页面

前期工作:Mac搭建 php 网页操作本地 mysql 数据库1 —— 环境搭建和一个小例子

新建一个add.php文件
代码如下:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>添加信息</title>
</head>

<script language="javascript">

  function chkinput(form)
   {
   
     if(form.name.value=="")
	 {
   
	   alert("请输入姓名!");
	   form.name.select();
	   return(false);
	 }
	   
     if(form.age.value=="")
	 {
   
	   alert("请输入年龄!");
	   form.age.select();
	   return(false);
	 }
	   
	 return(true);
   }

</script>
	
<body>
	<form name="form1" method="POST" action="saveadd.php" onSubmit="return chkinput(this)">
	<table width="200" border="1">
  <tbody>
    <tr>
      <th scope="row">name</th>
      <td><input type="text" name="name" id="name"></td>
    </tr>
    <tr>
      <th scope="row">age</th>
      <td><input type="text" name="age" id="age"></td>
    </tr>
    <tr>
      <th scope="row"></th>
      <td><input type="submit" name="button" id="button" value="提交">&nbsp;&nbsp;<input type="reset" name="button2" id="button2" value="重置"></td>
    </tr>
  </tbody>
</table>
		</form>
</body>
</html>

效果如下:

代码中的javascript函数是用来确认提交时输入不能为空

点击提交的时候调用saveadd.php在数据库中添加数据

操作数据库

saveadd.php代码

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<?php
 include("conn.php");//连接数据库

 $name=$_POST['name'];
 $age=$_POST['age'];
 mysqli_query($conn,"insert into info (name,age) values ('$name','$age')");

 echo "<script>alert('添加成功!');history.back();</script>";

?>

这里连接数据库调用了conn.php,将获取到的表格中的name和age传递到数据库的表info中

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>

<body>
	<?php
$conn=mysqli_connect("localhost","root","","test");
?>
</body>
</html>

结果

以上操作之后,打开127.0.0.1/test,和dw当前的add页面,同时确保XAMPP服务打开,开始添加数据

点击提交显示添加成功

去看一下主页,ok了

参考书:PHP7.0+mysql网站开发全程实例


转载:https://blog.csdn.net/qq_37813206/article/details/116909224
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场