當前位置:首頁 » 編程語言 » 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)
?>
熱點內容
request獲得伺服器ip 發布:2025-02-28 09:57:56 瀏覽:821
c讀取資料庫中圖片 發布:2025-02-28 09:52:50 瀏覽:650
愛豆里的視頻怎麼緩存 發布:2025-02-28 09:33:47 瀏覽:858
境外伺服器和虛擬ip 發布:2025-02-28 09:31:33 瀏覽:655
液晶電視存儲器 發布:2025-02-28 09:23:50 瀏覽:920
學習linux先學什麼 發布:2025-02-28 09:22:16 瀏覽:347
在cmd輸什麼可以查電腦配置 發布:2025-02-28 09:08:25 瀏覽:309
搭建共享文件存儲空間 發布:2025-02-28 09:03:48 瀏覽:825
android線程handler 發布:2025-02-28 09:03:44 瀏覽:408
短鏈接生成源碼 發布:2025-02-28 08:56:43 瀏覽:775