怎么用php把html表单内容写入数据库

怎么用php把html表单内容写入数据库,第1张

1:首先要使用PHP的超全局变量 $_GET 和 $_POST 用于收集表单数据(form-data)

2:然后使用INSERT INTO 语句用于向数据库表中插入新记录。

具体示例:

(1)首先创建了一个名为 "Persons" 的表,有三个列:"Firstname", "Lastname" 以及 "Age"。

<?php

$con = mysql_connect("localhost","peter","abc123")

if (!$con)

  {

  die('Could not connect: ' . mysql_error())

  }

mysql_select_db("my_db", $con)

mysql_query("INSERT INTO Persons (FirstName, LastName, Age) 

VALUES ('Peter', 'Griffin', '35')")

mysql_query("INSERT INTO Persons (FirstName, LastName, Age) 

VALUES ('Glenn', 'Quagmire', '33')")

mysql_close($con)

?>

(2)其次创建一个 HTML 表单,这个表单可把新记录插入 "Persons" 表。

<html>

<body>

<form action="insert.php" method="post">

Firstname: <input type="text" name="firstname" />

Lastname: <input type="text" name="lastname" />

Age: <input type="text" name="age" />

<input type="submit" />

</form>

</body>

</html>

(3)接着当用户点击上例中 HTML 表单中的提交按钮时,表单数据被发送到 "insert.php"。"insert.php" 文件连接数据库,并通过

$_POST 变量从表单取回值。然后,mysql_query() 函数执行 INSERT INTO 语句,一条新的记录会添加到数据库表中。

<?php

$con = mysql_connect("localhost","peter","abc123")

if (!$con)

  {

  die('Could not connect: ' . mysql_error())

  }

mysql_select_db("my_db", $con)

$sql="INSERT INTO Persons (FirstName, LastName, Age)

VALUES

('$_POST[firstname]','$_POST[lastname]','$_POST[age]')"

if (!mysql_query($sql,$con))

  {

  die('Error: ' . mysql_error())

  }

echo "1 record added"

mysql_close($con)

?>

最简单的方法:

1、先建立一个文件用于接收文件内用。001.HTML

<form name="form1" method="post" action="002.asp">

在下面输入文章内容:</p>

<p>

<textarea name="name" id="textarea" cols="45" rows="5"></textarea>

</p>

<input type="submit" name="Submit" value="提交">

<input type="reset" name="Submit2" value="重置">

</form>

再建立如下写入数据库的文件002.asp

<%

set conn=server.createobject("adodb.connection")

conn.open "driver={microsoft access driver (*.mdb)}dbq="&server.mappath("123.mdb")

name=request.form("name")

exec="insert into guestbook

(name)values('"+name+"')"

conn.execute exec

conn.close

set conn=nothing

rs.close

set rs=nothing

conn.close

set conn=nothing

response.write "记录添加成功!"

%>

数据库里要有name的字段。

*** 作时将浏览的网页中的内容拷贝,然后粘贴到001.HTML文件中的文件表单中,然后提交就到了数据库中。

比较简单你试试看。

要想高级一点的到网上下载个小偷程序参考一下。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/sjk/9560685.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-29
下一篇2023-04-29

发表评论

登录后才能评论

评论列表(0条)

    保存