目錄
1. Establish a Database Connection
2. Prepare and Execute the INSERT Statement
3. Handle Errors and Close Connection
首頁 後端開發 php教程 如何使用PHP將數據插入MySQL表中?

如何使用PHP將數據插入MySQL表中?

Sep 26, 2025 am 03:03 AM
mysql php

建立PDO數據庫連接,確保設置異常模式;2. 使用預處理語句插入數據,通過bindParam綁定參數防止SQL注入;3. 執行語句並處理錯誤,腳本結束自動關閉連接。安全插入數據的關鍵是連接、準備、綁定和執行。

How to insert data into a MySQL table using PHP?

To insert data into a MySQL table using PHP, you need to establish a connection to the database and execute an INSERT SQL statement. The most secure and recommended way is by using prepared statements to prevent SQL injection attacks.

1. Establish a Database Connection

Use the PDO or MySQLi extension to connect to your MySQL database. Here's an example using PDO:

try {
    $pdo = new PDO("mysql:host=localhost;dbname=your_database", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

2. Prepare and Execute the INSERT Statement

Use a prepared statement to safely insert user-provided data. This separates SQL logic from data.

$sql = "INSERT INTO users (name, email, age) VALUES (:name, :email, :age)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':age', $age);

// Set parameters and execute
$name = "John Doe";
$email = "john@example.com";
$age = 30;
$stmt->execute();

echo "New record inserted successfully";

3. Handle Errors and Close Connection

Always handle possible errors and let the connection close automatically (PDO/MySQLi will close when script ends). For manual control, you can set the variable to null.

if ($stmt->execute()) {
    echo "Record added.";
} else {
    echo "Error: " . implode(", ", $stmt->errorInfo());
}

Using prepared statements ensures your application remains secure even when inserting dynamic or user-submitted data.

Basically just connect, prepare, bind, and execute. That's the safe way to do it.

以上是如何使用PHP將數據插入MySQL表中?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT

Stock Market GPT

人工智慧支援投資研究,做出更明智的決策

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

漫天星漫畫完整版入口_滿天星漫畫去廣告特別版鏈接 漫天星漫畫完整版入口_滿天星漫畫去廣告特別版鏈接 Sep 28, 2025 am 10:30 AM

漫天星漫畫完整版入口為https://www.mantianxingmh.com,平台涵蓋熱血、戀愛、懸疑、科幻等多種題材,資源豐富且更新及時,支持分類檢索;提供高清畫質、多種翻頁模式、自定義背景與亮度調節,具備護眼模式優化閱讀體驗;用戶可創建書架、保存閱讀記錄、離線下載並實現跨設備同步進度。

如何在PHP MySQL中獲取最後一個插入的ID? 如何在PHP MySQL中獲取最後一個插入的ID? Sep 28, 2025 am 05:57 AM

使用mysqli_insert_id()(過程風格)、$mysqli->insert_id(對像風格)或$pdo->lastInsertId()(PDO)可獲取最後插入的ID,需在同連接中立即調用以確保准確性。

如何在MySQL中寫一個子查詢 如何在MySQL中寫一個子查詢 Sep 29, 2025 am 02:52 AM

SubqueryinMySQLallowsnestingqueries,wheretheinnerqueryrunsfirstanditsresultisusedbytheouterquery.ItcanbeappliedinSELECT,FROM,WHERE,andHAVINGclauses.IntheWHEREclause,itfiltersdata,suchasfindingemployeeswithsalariesabovetheaverage:SELECT*FROMemployeesW

如何在PHP中迴聲HTML標籤 如何在PHP中迴聲HTML標籤 Sep 29, 2025 am 02:25 AM

使用單引號或轉義雙引號在PHP中輸出HTML,推薦用單引號包裹字符串以避免屬性引號衝突,可結合變量拼接或heredoc語法生成動態內容。

MBTI免費測試官網入口_ MBTI測試免費網站網址鏈接 MBTI免費測試官網入口_ MBTI測試免費網站網址鏈接 Sep 28, 2025 am 10:00 AM

MBTI免費測試官網入口是https://www.16personalities.com/,該網站提供中英文版本測試,涵蓋性格維度分析、個性化報告及多場景應用建議,幫助用戶深入了解自身人格類型。

如何使用PHP中的GET請求變量? 如何使用PHP中的GET請求變量? Sep 29, 2025 am 01:30 AM

Use$_GETtoaccessURLquerystringvariablesinPHP,suchasname=Johnandage=30fromhttps://example.com/search.php?name=John&age=30;alwaysvalidateandsanitizeinputsusingfilter_input()andavoidsensitivedatainURLsduetoexposurerisks.

如何在MySQL中使用Cocece功能 如何在MySQL中使用Cocece功能 Sep 29, 2025 am 05:34 AM

COALESCE返回第一個非NULL值,用於處理空值替代;例如COALESCE(middle_name,'N/A')將NULL替換為'N/A',支持多字段回退及數據類型優先級判斷。

如何在PHP中使用最終類和方法? 如何在PHP中使用最終類和方法? Sep 28, 2025 am 05:55 AM

finalClassEndMethodsInphpprevEntinHeritanceanDoverRidingToprotectecticalCode.2.afinalClassCannotBexended,確保behaviormainsunchanged.3.afinalmethodcannodcannodcannodcannodcannotbeoverridden,preserervingConsistentImpplementImpplementActatimpplentatimplectationAccsSssSssSsSsSsSsSsSsSsSsSsseClass.4.4.usefinalfinalfinalfinalfinalfinalfilitfinalfilit

See all articles