---
# System prepended metadata

title: 筆記(七)簡易表單匯入資料庫
tags: [mysql, php]

---

---
title: 筆記(七)簡易表單匯入資料庫
tags: php,mysql
---

## 簡易表單匯入資料庫
### 前置作業
要做哪些東西
* form表單
* php後端
* 連線mysql

### 實作
> 先從[bootstrap的form](https://getbootstrap.com/docs/4.6/components/forms/#overview)複製一個表單樣本，寫進index.php裡面，表單送出後會進到update.php裡面。[color=#907bf7]

```htmlmixed!
<!---index.php--->
<html>
<head>
    //引入bootstrap
    ...
    <title>表單</title>
</head>
<body>
<div class="container">
<form class="form-login" action="update.php" method="POST">
    
  <div class="form-group">
    <label for="inputEmail">Email address</label>
    <input type="email" class="form-control" id="inputEmail" name="email" required>
  </div>
  
  <div class="form-group">
    <label for="inputPass">Password</label>
    <input type="password" class="form-control" id="inputPass" name="pwd" required>
  </div>
  
  <button type="submit" class="btn btn-primary">Submit</button>
  
</form>
</div>
    
</body>
</html>
```

> 關於updata.php接收表單資料併存進資料庫[color=#907bf7]
> > 先在mysql裡面建立一個資料庫和資料表，到時直接連上即可存入[color=orange]
```php!
<!---update.php--->
//connect mysql
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";



//POST資料 addslashes防止sql注入攻擊
$p_email = addslashes($_POST["email"]);
//password需要加密
$p_pwd = password_hash(addslashes($_POST["pwd"]), PASSWORD_BCRYPT);

//insert database
$add_sql = "INSERT INTO `資料表名稱` (`email`, `password`) 
    VALUES (
    '$p_email',
    '$p_pwd',
    )
    ";

if($conn->query($add_sql) == true){
    echo 'successful!';  //成功
}else{
    echo 'error: ' . $add_sql . "<br>" . $conn->error;; //列出失敗因素
}

?>

```
:::success
表單已存入資料庫了!:tada:
:::
## 關於表單送出要驗證兩欄密碼是否相同：
> 通常建立創建帳密的表單，因為設計上載密碼部分 ==type="password"== 防止使用者看到自己輸入些什麼，所以會再建立一個欄位重複確認密碼是否吻合。[color=#907bf7]

> 會應用js語法讓表單在送出的時候觸發function，執行檢查動作。[color=red]
> 以下是 ==更改過的index.php form部分==

```htmlmixed!
<head>
    //引入bootstrap
    ...
    <title>表單</title>
    
    //新增 on_submit() function
    <script>
    function on_submit(){
        var pwd = document.getElementById('inputPass');
        var repwd = document.getElementById('rePass');
        if(pwd.value != repwd.value){
            alert('密碼不一致');
            pwd.value = "";
            repwd.value = "";
            pwd.focus();
            return false;
        }
    }
    </script>
</head>
<body>
<div class="container">
    //新增 onsubmit="return on_submit()"
<form class="form-login" action="update.php" method="POST" onsubmit="return on_submit()">
    
  <div class="form-group">
    <label for="inputEmail">Email address</label>
    <input type="email" class="form-control" id="inputEmail" name="email" required>
  </div>
  
  <div class="form-group">
    <label for="inputPass">Password</label>
    <input type="password" class="form-control" id="inputPass" name="pwd" required>
  </div>
    
  <div class="form-group">
    <label for="inputPassVerify">Check Password</label>
    <input type="password" class="form-control" id="rePass" required>
  </div>
  
  <button type="submit" class="btn btn-primary">Submit</button>
  
</form>
</div>
    
</body>
```
:::warning
:warning:onsubmit 是一個 HTML form 表單事件，在表單提交時觸發，通常用於在提交前進行表單驗證或者對表單數據進行處理。
:::

## 關於禁止用Enter將表單送出：
```javascript!
<script language="javascript" type="text/javascript">  
 //禁用Enter 
        document.onkeydown = function(event) {  
            var target, code, tag;  
            if (!event) {  
                event = window.event; //for ie  
                target = event.srcElement;  
                code = event.keyCode;  
                if (code == 13) {  
                    tag = target.tagName;  
                    if (tag == "TEXTAREA") { return true; }  
                    else { return false; }  
                }  
            }  
            else {  
                target = event.target; //for w3c
                code = event.keyCode;  
                if (code == 13) {  
                    tag = target.tagName;  
                    if (tag == "INPUT") { return false; }  
                    else { return true; }  
                }  
            }  
        };  
</script>  
```


這樣一個如何建立表單，存進資料庫和密碼驗證都已完成。

