Linux下MySQL数据库与表的基础创建
以下展示了在Linux系统中登录MySQL、创建数据库以及建表的完整操作流程。
yin@yin-Ubuntu10:~$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 360
Server version: 5.1.41-3ubuntu12.1 (Ubuntu)
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> create database UseCase;
Query OK, 1 row affected (0.00 sec)
mysql> use UseCase;
Database changed
mysql> create table User(UserName varchar(20) primary key,Password varchar(20) not null,CreateTime timestamp default current_timestamp);
Query OK, 0 rows affected (0.01 sec) 接下来我们将创建一个页面来实现新建用户的功能。首先需要一个基础的HTML表单:
<form action="db.php" method="post"> <br><dl> <br><dt>UserName</dt><dd><input name="UserName" maxlength="20" type="text"></dd> <br><dt>Password</dt><dd><input name="Password" maxlength="20" type="password"></dd> <br><dt>Confirm Password</dt><dd><input name="ConfirmPassword" maxlength="20" type="password"></dd> <br></dl> <br><input type="submit" name="ok" value="ok"> <br></form> PHP利用$_POST数组接收通过POST方法提交的表单数据。在PHP脚本中,首先需要检查是否存在ok字段,以此区分是首次访问页面还是用户点击提交按钮后的动作,随后验证两次输入的密码是否一致。确认无误后,即可获取用户名和密码并将其插入数据库。PHP连接MySQL通常可选用mysql或mysqli扩展,鉴于mysqli更新且功能更完善,此处选用该方式。虽然mysqli可能需要安装配置,但在当前环境中已默认就绪。使用mysqli操作数据库主要步骤包括:实例化mysqli对象、准备statement、绑定参数、执行查询以及关闭连接。具体代码如下:
<?php
$match=true;
if(isset($_POST["ok"])) {
$pwd=$_POST["Password"];
$pwdConfirm=$_POST["ConfirmPassword"];
$match=($pwd==$pwdConfirm);
$conn=new mysqli("localhost","root","123","UseCase");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query="insert into User(UserName,Password) values(?,?)";
$stmt=$conn->stmt_init();
$stmt->prepare($query);
$stmt->bind_param('ss',$name,$pwd);
$name=$_POST["UserName"];
$pwd=$_POST["Password"];
$stmt->execute();
if($stmt->errno==0) {
$success=true;
}else {
$success=false;
}
$stmt->close();
$conn->close();
}
?> 其中bind_param方法需稍作说明,其第一个参数用于指定参数类型。每个字符对应一个待绑定的参数,s代表字符串,i代表整数,d代表浮点数,b代表blob类型。最后,为页面添加相应的提示信息:
<?php
if(!$match) { ?>Password and Confirm Password must match.
<?php
}
?> <?php
if(isset($success)) {
if($success) {
echo '
User Created Successfully!';
}elseif($sucess==false) {
echo '
User Name existed.';
}
}
?>
接下来,我们将编写一个展示用户列表的页面。
复制代码 代码如下:| User Name | CreateTime | Action |
|---|---|---|
| <?= $row['UserName'] ?> | <?= date('Y-m-d',strtotime($row['CreateTime']))?> | ">Edit ">Delete |