前端php与数据库(MySQL)的连接和常用操作

数据库

数据库是按照数据结构来组织、存储和管理数据的仓库

数据类型

Int 数值

varchar(可变字符串)/char (不可变字符串)

date 日期

数据库相关操作

创建表

create table 表名 (字段 类型 ,字段 类型....)

例:

create table student( stuid int primary key,(不能重复) stuname varchar(10) not null,(不能为空))

增加记录

insert into 表名 values(值1,值2...)

删除记录

delete from 表名 where 字段=值 and(or) 字段=值

查找记录

select * from 表名 where 字段=值

例:

select*from student where stu_id>3; where stu_name like"%王%";模糊查询 where stu_id<5 and stu_age>5;

改记录

update 表名 set 字段=值,字段=值

where 字段=值


php连接控制数据库

创建数据库连接对象

$conn=mysql_connect("localhost","root","root")

选择数据库

mysql_select_db("数据库名")

操作数据库

mysql_query("sql语句",$conn)

ps:

sql语句如果是增删改的话返回值为受影响记录的个数

sql语句如果是查的话返回值为结果集

需要配合mysql_num_rows(结果集)使用 返回的是结果集的记录个数,通常用于验证用户输入的账号密码:

<?php
	header("Content-type:text/html;charser=utf-8");
	$name=$_GET["username"];
	$conn=mysql_connect("localhost","root","root");
	mysql_select_db("测试数据库");
	$result=mysql_query("select * from user where name=$name",$conn);
	if(mysql_num_rows($result)==1){
		echo "注册失败,用户名已存在";
	}else{
		echo "可以注册";
	}

?>

或配合mysql_fetch_assoc(结果集)使用

返回的是当前游标所指记录的对象,该函数执行一遍后,游标自动下移

例(打印所有字段的值):

$result=mysql_query("select*from student");

while($obj=mysql_fetch_assoc($result)){ echo $obj["stu_id"]." ".$obj["stu_name"]." ".$obj["stu_gender"]." ".$obj["stu_date"];}

断开连接

mysql_close($conn)

经验分享 程序员 微信小程序 职场和发展