数据库的连接
cmd模式下:
切换到mysql.exe所在目录下输入命令:mysql -h主机名 -u用户名 -p密码
php连接:
面向对象的方法:@ $db=new mysqli("主机名“,“用户名”,“密码”,“数据库名”);实例化了mysqli类并创建了到主机的连接,创建了一个对象
面向过程的方法:@ $db=mysqli_connect("主机名“,“用户名”,“密码”,“数据库”);返回一个资源(表示到数据库的连接)
检查连接if(mysqli_connect_errno()){
echo "error:counnot connect;
exit; }连接错误时,返回以错误号,成功,返回0;
创建并使用数据库
cmd模式下:
创建:create database dbname;
使用:use dbname;
php下:
面向对象:$db->select_db(dbname);
面向过程:$db=mysqli_select_db($db,dbname);
创建数据库表(默认存储引擎MyISAM)
cmd模式下:
create table tablename(columns);
查看数据库
cmd下:
列出所有数据库:show databases;
描述其中某一数据库:describe dbname;
列出所有的数据库表:show tables;
在数据库中插入数据
cmd下:
insert into table (column1,column2,column3.。。。)values(value1,value2,value3.。。。。);
只记录某些字段时:insert into table set colum1=value1,column2=value2.。。;
php下:
$query='insert into tablename(column1,column2.。。)values('','','')';
$result=$db->query();
在数据库中获取数据
cmd下:
获取全部数据:select * from tablename;
获取某一个键的数据: select column1 ,column2 from tablename;
获取某一条数据:select * where column1=value1;
php下:
$query="select *from tablename where...";
面向对象:$result=$db->query($query);
面向过程:$result=mysqli_query($db,$query);
检索:
获取查询记录集:mysqli_result($result,row,fied)row:行号规定从0开始,field:某个字段
获得当前行数据:mysqli_fetch_row($result);row[0],row[1]...通过偏移量访问
以数组的形式返回:mysqli_fetch_array($result);
以对象返回:mysqli_fetch_object($result);只能通过字段名访问,而不是偏移量
修改数据库记录
cmd下:
删除:delete from tablename where。。。;
表的删除:drop table tablename;
数据库的删除:drop database dbname;
更新:update tablename set column1=value1 where。。。;
更改表的数据类型:alter table tablename modify column 新数据类型(大小);
增加新的一列:alter table tablename add column 数据类型(大小)after column1;
删除一列:alter table tablename drop column;
退出
释放结果集$result->free();或mysqli_free_result($result);
然后关闭数据库:$db->close()或mysqli_close($db);