基本语法
- mysqli_connect() 函数来连接数据库。
- mysqli_select_db() 来选取一个数据库。
- mysqli_query() 执行sql语句
mysql控制台操作
//创建test表
mysql> create table test(
-> id int not null default 0 comment 'id号',
-> name varchar(60) not null default '' comment '用户名',
-> sex enum('男','女') not null comment '性别',
-> birthday date not null comment '生日',
-> entry_date date not null comment '入职时间',
-> job varchar(60) not null default '' comment '工作',
-> salary float not null default 0.0 comment '薪水',
-> resume text not null comment '个人介绍'
-> )charset=utf8 engine=myisam;
Query OK, 0 rows affected (0.06 sec)
//插入两条数据
mysql> insert into test values(1, '赵信', 1, '2010-11-11', '2018-12-12', '管家', 8000.55, '一点寒芒先到,随后枪出如龙');
Query OK, 1 row affected (0.00 sec)
mysql> insert into test values(2, '阿卡丽', 2, '2013-03-03', '2019-09-09', '刺客', 5555.55, '我随影而来,随影而去');
Query OK, 1 row affected (0.00 sec)
//查询数据
mysql> select * from test;
+----+--------+-----+------------+------------+------+---------+----------------------------+
| id | name | sex | birthday | entry_date | job | salary | resume |
+----+--------+-----+------------+------------+------+---------+----------------------------+
| 1 | 赵信 | 男 | 2010-11-11 | 2018-12-12 | 管家 | 8000.55 | 一点寒芒先到,随后枪出如龙 |
| 2 | 阿卡丽 | 女 | 2013-03-03 | 2019-09-09 | 刺客 | 5555.55 | 我随影而来,随影而去 |
+----+--------+-----+------------+------------+------+---------+----------------------------+
2 rows in set (0.00 sec)
使用php查询
<?php
//链接数据库
$con = mysqli_connect('localhost', 'root', '');
if(!$con){
die('错误信息'.mysqli_error($con));
}
echo '数据库链接成功','<br>';
//设置编码 防止乱码
mysqli_query($con,'set names utf8');
//选择数据库
mysqli_select_db($con,'people');
//查询数据
$sql = "select * from test";
$res = mysqli_query($con, $sql);
if (!$res){
die('无法读取数据'.mysqli_error($con));
}
echo '数据读取成功','<br>';
//显示数据库的数据
echo "<table style=\"border:1px solid;width:400px\">";
echo "<tr><th>id号</th><th>姓名</th><th>薪水</th><th>介绍</th></tr>";
while ($row = mysqli_fetch_assoc($res)){
/*echo '<pre>';
var_dump($row);*/
echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td><td>{$row['salary']}</td><td>{$row['resume']}</td></tr>";
}
echo "</table>";
//如果不写这两句话,页面执行完毕,系统会自动释放和关闭链接
//释放资源
mysqli_free_result($res);
//关闭资源
mysqli_close($con);