mysql:php操作mysql基础总结

知识点

  • 查询语句得到的是一个结果集,增删改得到的是影响的行数
  • 删除一行数据,主键 id 不会自动变化

基本操作

查询:
select id, name from users;
# 带上反引号可避免一些关键字冲突
select `id`, `name` from `users`;
# 使用通配符会全表扫描,不推荐
select * from users;
# 可以选择一个具体的值
select 'foo' from users;
新增:
# value 加不加 s 都可以
insert into users values (null, 'CEO', '张三', 12);
insert into users value (null, 'CEO', '张三', 12);
# 一一对应
insert into users (title, name, age) values ('CEO', '张三', 12);
删除:
# 删除语句一定要带上数据筛选(where)
delete from users where title='ufo' and id>1
delete from users where id in (1,2,3,4)
修改:
update users set title = 'CEO', name = '张三' where id = 1

常见查询函数

# 总条数:
select count(id) from users;
# 最大值:
select max(id) from users;
# 限制两条,默认前两条:
select * from users limit 2;
# 限制两条,排序为越过4条取2条:
# limit <skip>, <length>
# skip = (page - 1) * length
select * from users limit 4, 2;

php操作

# 连接,mysqli是mysql的升级版,但是一个扩展
$connection = mysqli_connet('127.0.0.1', 'root', '1234', 'user')

// 1. 必须在查询数据之前
// 2. 必须传入连接对象和编码
mysqli_set_charset($connection, 'utf8');
// mysqli_query($connection, 'set names utf8;');

if (!$connection) {
  // 连接数据库失败
  exit('<h1>连接数据库失败</h1>');
}

// 得到的是一个查询对象,这个查询对象可以用来再到数据一行一行拿数据
$query = mysqli_query($connection, 'select * from users')

// 一次一次的去拿数据,一次拿一行,所以要遍历
while ($row = mysqli_fetch_assoc($query)) {
  var_dump($row);
}

// 释放查询结果集
mysqli_free_result($query);

// 炸桥 关闭连接
mysqli_close($connection);
// 基于刚刚创建的连接对象执行一次查询操作
$query = mysqli_query($connection, 'delete from users where id = 5;');

if (!$query) {
  exit('<h1>查询失败</h1>');
}

// 如何拿到受影响行
// 传入的一定是连接对象
$rows = mysqli_affected_rows($connection);

发布了165 篇原创文章 · 获赞 59 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_43972437/article/details/103658695