执行原生SQL语句


执行查询SQL语句

执行查询语句

  1. /**
  2. * 执行查询语句
  3. *
  4. * @param $sql 执行的SQL语句
  5. * @param null $params 绑定的参数
  6. * @param null $row_type 返回单行还是多行,默认多行
  7. * @param int $fetch_mode 获取模式
  8. * @return array|\PDOStatement
  9. */
  10. query($sql, $params, $row_type, $fetch_mode)
  11. $users = $db->query('SELECT * FROM user WHERE type = 2');

获取单条(对query方法的封装)

  1. $user = $db->one('SELECT * FROM user WHERE id = 1 LIMIT 1');
  2. var_dump($user);
  3. //使用参数绑定
  4. $user = $db->one('SELECT * FROM user WHERE id = ? LIMIT 1', [1]);

获取多条(对query方法的封装)

  1. $users = $db->all('SELECT * FROM user where cid > 2 status = 1 LIMIT 5');
  2. var_dump($rows);
  3. //使用参数绑定
  4. $users = $db->all('SELECT * FROM user where cid > ? status = ? LIMIT 5', [2, 1]);

执行非查询SQL语句

  1. $sql = "UPDATE timo_user SET nickname = ? WHERE id = ?";
  2. $affected_rows = $db->execute($sql, ['tommy8', 1], true);
  3. if ($affected_rows !== false) {
  4. echo '更新成功';
  5. } else {
  6. echo '更新失败';
  7. }

获取最新的insert_id

  1. $insert_id = $db->lastInsertId();