php寫了一個簡單的用戶注冊頁面。本篇結合前一篇的內容,將注冊頁面上提交的信息post 給後面的頁面register.php ,register.php將post的信息提交入庫。
一、創建數據庫與表結構
1、建庫
mysql> create database 361way character set utf8;
Query OK, 1 row affected (0.00 sec)
上面我建了一個同我站點同命的庫361way 。
2、創建表結構
CREATE TABLE IF NOT EXISTS `tblmember` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fName` varchar(30) NOT NULL,
`lName` varchar(30) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(60) NOT NULL,
`birthdate` text NOT NULL,
`gender` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=10 ;
這裡的字符編碼我選擇的是utf8 ,並且在該表的id值是從11開始的(前面預留了10個),數據庫引擎類型用的InnoDB,具體可以根據自己的需求修改。
二、post提交php頁面
向後端提交post請求的register.php代碼如下:
<?php
//set up mysql connection
mysql_connect("localhost", "root", "123456") or die(mysql_error());
//select database
mysql_select_db("361way") or die(mysql_error());
//get the value from the posted data and store it to a respected variable
$fName = $_POST['fName'];
$lName = $_POST['lName'];
$email = $_POST['email'];
$reemail = $_POST['reemail'];
$password = sha1($_POST['password']);
$month = $_POST['month'];
$day = $_POST['day'];
$year = $_POST['year'];
$gender = $_POST['optionsRadios'];
$birthdate = $year . '-' . $month . '-' . $day;
//insert data using insert into statement
$query = "INSERT INTO tblmember(id, fName, lName, email, password, birthdate, gender)
VALUES (NULL, '{$fName}', '{$lName}', '{$email}', '{$password}', '{$birthdate}', '{$gender}')";
//execute the query
if (mysql_query($query)) {
//dislay a message box that the saving is successfully save
echo "<script type=\"text/javascript\">
alert(\"New member added successfully.\");
window.location = \"registration.php\"
</script>";
} else
die("Failed: " . mysql_error());
?>
上面的代碼使用時,數據庫的用戶名密碼及庫名根據實際情況修改。
三、測試代碼
按上一篇的注冊頁面輸入相關信息並提交後,會彈出如下信息,表示注冊成功:
register-mysql
再看下mysql 裡的信息:
mysql> select * from tblmember;
+----+-------+-------+------------------+------------------------------------------+-------------+--------+
| id | fName | lName | email | password | birthdate | gender |
+----+-------+-------+------------------+------------------------------------------+-------------+--------+
| 10 | test | yang | [email protected] | a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 | 1997-Jan-28 | Female |
| 11 | aaa | bbb | [email protected] | 54df472f438b86fc96d68b8454183394ef26b8ac | 1997-Jan-18 | Female |
+----+-------+-------+------------------+------------------------------------------+-------------+--------+
2 rows in set (0.00 sec)
我執行了兩次注冊,這裡有兩台記錄。