php向mysql插入數據


<?php
//設置編碼格式
header("Content-type:text/html;charset=utf-8");
//設備變量
$servername = "localhost";  
$username = "root";  
$password = "root";  
$dbname = "test";  
//獲取傳遞值:$_GET['name'] 或$_POST['name'] 
$id = $_GET['id'];
$name = $_GET['name'];
$age = $_GET['age'];
$sex = $_GET['sex'];
// 創建連接  
$con =mysqli_connect($servername, $username, $password, $dbname);
$sql="INSERT INTO `表名稱`(`字段1`, `字段2`, `字段3`, `字段4`) VALUES ("$id","$name","$age","$sex")";
$result = mysqli_query($con,$sql); 
if($result) echo "添加成功!";
else echo "添加失敗!";
mysqli_close($con);
?>

 

把來自表單的數據插入數據庫

現在,我們創建一個 HTML 表單,這個表單可把新記錄插入 "Persons" 表。

這是這個 HTML 表單:

<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>

當用戶點擊上例中 HTML 表單中的提交按鈕時,表單數據被發送到 "insert.php"。"insert.php" 文件連接數據庫,並通過 $_POST 變量從表單取回值。然后,mysql_query() 函數執行 INSERT INTO 語句,一條新的記錄會添加到數據庫表中。

下面是 "insert.php" 頁面的代碼:

<?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)
?>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM