- PHP & MySQL 教程
- PHP & MySQL - 首頁
- PHP & MySQL - 概述
- PHP & MySQL - 環境搭建
- PHP & MySQL 示例
- PHP & MySQL - 連線資料庫
- PHP & MySQL - 建立資料庫
- PHP & MySQL - 刪除資料庫
- PHP & MySQL - 選擇資料庫
- PHP & MySQL - 建立表
- PHP & MySQL - 刪除表
- PHP & MySQL - 插入記錄
- PHP & MySQL - 選擇記錄
- PHP & MySQL - 更新記錄
- PHP & MySQL - 刪除記錄
- PHP & MySQL - WHERE 子句
- PHP & MySQL - LIKE 子句
- PHP & MySQL - 資料排序
- PHP & MySQL - 使用 JOIN
- PHP & MySQL - 處理 NULL 值
- PHP & MySQL - 資料庫資訊
- PHP & MySQL 有用資源
- PHP & MySQL - 快速指南
- PHP & MySQL - 有用資源
- PHP & MySQL - 討論
PHP & MySQL - 插入記錄示例
PHP 使用 `mysqli_query` 函式將記錄插入表中。此函式接受三個引數,成功時返回 TRUE,失敗時返回 FALSE。
語法
mysqli_query ( mysqli $link, string $query, int $resultmode = MYSQLI_STORE_RESULT ) : mixed
| 序號 | 引數 & 描述 |
|---|---|
| 1 |
$link 必需 - 由 `mysqli_connect()` 或 `mysqli_init()` 返回的連結識別符號。 |
| 2 |
$query 必需 - 刪除表的 SQL 查詢。 |
| 2 |
$resultmode 可選 - 常量 `MYSQLI_USE_RESULT` 或 `MYSQLI_STORE_RESULT` 之一,取決於所需的行為。預設情況下,使用 `MYSQLI_STORE_RESULT`。 |
示例
此示例將從使用者處獲取三個引數,並將它們插入 MySQL 表中:
複製並貼上以下示例作為 mysql_example.php:
<html>
<head>
<title>Add New Record in MySQL Database</title>
</head>
<body>
<?php
if(isset($_POST['add'])) {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root@123';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysqli_error($conn));
}
if(! get_magic_quotes_gpc() ) {
$tutorial_title = addslashes ($_POST['tutorial_title']);
$tutorial_author = addslashes ($_POST['tutorial_author']);
} else {
$tutorial_title = $_POST['tutorial_title'];
$tutorial_author = $_POST['tutorial_author'];
}
$submission_date = $_POST['submission_date'];
$sql = "INSERT INTO tutorials_tbl ".
"(tutorial_title,tutorial_author, submission_date) "."VALUES ".
"('$tutorial_title','$tutorial_author','$submission_date')";
mysqli_select_db( $conn, 'TUTORIALS' );
$retval = mysqli_query( $conn, $sql );
if(! $retval ) {
die('Could not enter data: ' . mysqli_error($conn));
}
echo "Entered data successfully\n";
mysqli_close($conn);
} else {
?>
<form method = "post" action = "<?php $_PHP_SELF ?>">
<table width = "600" border = "0" cellspacing = "1" cellpadding = "2">
<tr>
<td width = "250">Tutorial Title</td>
<td><input name = "tutorial_title" type = "text" id = "tutorial_title"></td>
</tr>
<tr>
<td width = "250">Tutorial Author</td>
<td><input name = "tutorial_author" type = "text" id = "tutorial_author"></td>
</tr>
<tr>
<td width = "250">Submission Date [ yyyy-mm-dd ]</td>
<td><input name = "submission_date" type = "text" id = "submission_date"></td>
</tr>
<tr>
<td width = "250"> </td>
<td></td>
</tr>
<tr>
<td width = "250"> </td>
<td><input name = "add" type = "submit" id = "add" value = "Add Tutorial"></td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>
輸出
訪問部署在 Apache Web 伺服器上的 mysql_example.php,輸入詳細資訊,並在提交表單後驗證輸出。
Entered data successfully
在進行資料插入時,最好使用函式 `get_magic_quotes_gpc()` 來檢查當前魔術引號配置是否已設定。如果此函式返回 false,則使用函式 `addslashes()` 在引號前新增斜槓。
您可以進行許多驗證來檢查輸入的資料是否正確,並採取相應的操作。
廣告