當前位置:首頁 » 編程語言 » php資料庫html

php資料庫html

發布時間: 2025-01-01 06:22:51

Ⅰ 怎麼用php把html表單內容寫入資料庫

1:首先要使用PHP的超全局變數 $_GET 和 $_POST 用於收集表單數據(form-data)

2:然後使用INSERT INTO 語句用於向資料庫表中插入新記錄。

具體示例:

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

<?php
$con=mysql_connect("localhost","peter","abc123");
if(!$con)
{
die('Couldnotconnect:'.mysql_error());
}

mysql_select_db("my_db",$con);

mysql_query("INSERTINTOPersons(FirstName,LastName,Age)
VALUES('Peter','Griffin','35')");

mysql_query("INSERTINTOPersons(FirstName,LastName,Age)
VALUES('Glenn','Quagmire','33')");

mysql_close($con);
?>

(2)其次創建一個 HTML 表單,這個表單可把新記錄插入 "Persons" 表。

<html>
<body>

<formaction="insert.php"method="post">
Firstname:<inputtype="text"name="firstname"/>
Lastname:<inputtype="text"name="lastname"/>
Age:<inputtype="text"name="age"/>
<inputtype="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('Couldnotconnect:'.mysql_error());
}

mysql_select_db("my_db",$con);

$sql="INSERTINTOPersons(FirstName,LastName,Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

if(!mysql_query($sql,$con))
{
die('Error:'.mysql_error());
}
echo"1recordadded";

mysql_close($con)
?>
熱點內容
ftp和ssh什麼意思 發布:2025-09-17 16:46:18 瀏覽:496
安卓如何限定應用 發布:2025-09-17 16:35:50 瀏覽:383
pythoncmd退出命令 發布:2025-09-17 16:16:33 瀏覽:924
朗動頂配是什麼配置 發布:2025-09-17 16:08:35 瀏覽:443
小孩子學習編程 發布:2025-09-17 16:05:12 瀏覽:119
vivo手機怎樣關閉騰訊視頻緩存 發布:2025-09-17 16:03:24 瀏覽:264
手機內存和存儲空間 發布:2025-09-17 15:53:40 瀏覽:605
小米5怎麼升級安卓7 發布:2025-09-17 15:44:14 瀏覽:918
java培訓班一般要多少錢 發布:2025-09-17 15:39:34 瀏覽:165
腳本掛到寶塔看視頻 發布:2025-09-17 15:33:36 瀏覽:296