PHP学习笔记之三 数据库基本操作_PHP教程

WBOY
풀어 주다: 2016-07-21 15:32:16
원래의
763명이 탐색했습니다.

下面是在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)下面就来建立一个页面来完成新建用户的页面。首先是一个简单的表单:

复制代码代码如下:



UserName

Password

Confirm Password





PHP通过$_POST数组来获得通过post方法提交的表单中的数据。在PHP程序中,我们首先要判断是有OK字段,从而判断出该页面是首次访问,还是用户点击OK后提交的,接着判断两次密码输入是否统一。然后就可以获取到用户名和密码,插入数据库中。PHP连接MySQL数据库一般可以利用mysql扩展或者mysqli扩展,mysqli扩展比较新一点,这里我们采用这种方式。mysqli可能需要安装配置下,不过在我的环境中是默认装好的。利用mysqli扩展操作数据库一般分为如下几步:构造mysqli对象,构造statement,绑定参数,执行,关闭。代码如下:
复制代码代码如下:

$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。最后,再为这个页面添加一点提示信息:
复制代码代码如下:

if(!$match) { ?>

Password and Confirm Password must match.


}
?>
if(isset($success)) {
if($success) {
echo '

User Created Successfully!';
}elseif($sucess==false) {
echo '

User Name existed.';
}
}
?>


再接下来,我们编写一个用户列表页面。
复制代码代码如下:


















include 'conn.php';$query="select * from User;";$res=$mysql->query($query);while($row=$res->fetch_array()) {?> }$res->close();$mysql->close();?>
User Name CreateTime Action
= $row['UserName'] ?> = date('Y-m-d',strtotime($row['CreateTime']))?> Edit
Delete

www.bkjia.com true http://www.bkjia.com/PHPjc/322815.html TechArticle 下面是在Linux上登录mysql,创建数据库和创建表的过程。 yin@yin-Ubuntu10:~$ mysql -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \...
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!