MySQLI 함수 캡슐화를 기반으로 한 PHP 데이터베이스에 대한 자세한 설명

小云云
풀어 주다: 2023-03-19 17:16:02
원래의
2667명이 탐색했습니다.

이 글에서는 주로 MySQLI 함수 캡슐화를 기반으로 하는 PHP의 데이터베이스 연결 도구 클래스를 소개합니다. MySQLI 함수 캡슐화에 의해 구현되는 데이터베이스 작업 클래스 정의 및 연결, 추가, 삭제, 수정 및 쿼리와 기타 기본 작업 사용법을 분석합니다. 도움이 필요한 친구들이 모두 참고할 수 있기를 바랍니다.

mysql.class.php:


<?php
class mysql
{
  private $mysqli;
  private $result;
  /**
   * 数据库连接
   * @param $config 配置数组
   */
  public function connect($config)
  {
    $host = $config[&#39;host&#39;];    //主机地址
    $username = $config[&#39;username&#39;];//用户名
    $password = $config[&#39;password&#39;];//密码
    $database = $config[&#39;database&#39;];//数据库
    $port = $config[&#39;port&#39;];    //端口号
    $this->mysqli = new mysqli($host, $username, $password, $database, $port);
  }
  /**
   * 数据查询
   * @param $table 数据表
   * @param null $field 字段
   * @param null $where 条件
   * @return mixed 查询结果数目
   */
  public function select($table, $field = null, $where = null)
  {
    $sql = "SELECT * FROM {$table}";
    if (!empty($field)) {
      $field = &#39;`&#39; . implode(&#39;`,`&#39;, $field) . &#39;`&#39;;
      $sql = str_replace(&#39;*&#39;, $field, $sql);
    }
    if (!empty($where)) {
      $sql = $sql . &#39; WHERE &#39; . $where;
    }
    $this->result = $this->mysqli->query($sql);
    return $this->result->num_rows;
  }
  /**
   * @return mixed 获取全部结果
   */
  public function fetchAll()
  {
    return $this->result->fetch_all(MYSQLI_ASSOC);
  }
  /**
   * 插入数据
   * @param $table 数据表
   * @param $data 数据数组
   * @return mixed 插入ID
   */
  public function insert($table, $data)
  {
    foreach ($data as $key => $value) {
      $data[$key] = $this->mysqli->real_escape_string($value);
    }
    $keys = &#39;`&#39; . implode(&#39;`,`&#39;, array_keys($data)) . &#39;`&#39;;
    $values = &#39;\&#39;&#39; . implode("&#39;,&#39;", array_values($data)) . &#39;\&#39;&#39;;
    $sql = "INSERT INTO {$table}( {$keys} )VALUES( {$values} )";
    $this->mysqli->query($sql);
    return $this->mysqli->insert_id;
  }
  /**
   * 更新数据
   * @param $table 数据表
   * @param $data 数据数组
   * @param $where 过滤条件
   * @return mixed 受影响记录
   */
  public function update($table, $data, $where)
  {
    foreach ($data as $key => $value) {
      $data[$key] = $this->mysqli->real_escape_string($value);
    }
    $sets = array();
    foreach ($data as $key => $value) {
      $kstr = &#39;`&#39; . $key . &#39;`&#39;;
      $vstr = &#39;\&#39;&#39; . $value . &#39;\&#39;&#39;;
      array_push($sets, $kstr . &#39;=&#39; . $vstr);
    }
    $kav = implode(&#39;,&#39;, $sets);
    $sql = "UPDATE {$table} SET {$kav} WHERE {$where}";
    $this->mysqli->query($sql);
    return $this->mysqli->affected_rows;
  }
  /**
   * 删除数据
   * @param $table 数据表
   * @param $where 过滤条件
   * @return mixed 受影响记录
   */
  public function delete($table, $where)
  {
    $sql = "DELETE FROM {$table} WHERE {$where}";
    $this->mysqli->query($sql);
    return $this->mysqli->affected_rows;
  }
}
로그인 후 복사

사용 방법


<?php
require_once &#39;mysql.class.php&#39;;
/* 配置连接参数 */
$config = array(
  &#39;type&#39; => &#39;mysql&#39;,
  &#39;host&#39; => &#39;localhost&#39;,
  &#39;username&#39; => &#39;woider&#39;,
  &#39;password&#39; => &#39;3243&#39;,
  &#39;database&#39; => &#39;php&#39;,
  &#39;port&#39; => &#39;3306&#39;
);
/* 连接数据库 */
$mysql = new mysql();
$mysql->connect($config);
/* 查询数据 */
//1、查询所有数据
$table = &#39;mysqli&#39;;//数据表
$num = $mysql->select($table);
echo &#39;共查询到&#39; . $num . &#39;条数据&#39;;
print_r($mysql->fetchAll());
//2、查询部分数据
$field = array(&#39;username&#39;, &#39;password&#39;); //过滤字段
$where = &#39;id % 2 =0&#39;;          //过滤条件
$mysql->select($table, $field, $where);
print_r($mysql->fetchAll());
/* 插入数据 */
$table = &#39;mysqli&#39;;//数据表
$data = array(  //数据数组
  &#39;username&#39; => &#39;admin&#39;,
  &#39;password&#39; => sha1(&#39;admin&#39;)
);
$id = $mysql->insert($table, $data);
echo &#39;插入记录的ID为&#39; . $id;
/* 修改数据 */
$table = &#39;mysqli&#39;;//数据表
$data = array(
  &#39;password&#39; => sha1(&#39;nimda&#39;)
);
$where = &#39;id = 44&#39;;
$rows = $mysql->update($table, $data, $where);
echo &#39;受影响的记录数量为&#39; . $rows . &#39;条&#39;;
/* 删除数据 */
$table = &#39;mysqli&#39;;
$where = &#39;id = 45&#39;;
$rows = $mysql->delete($table, $where);
echo &#39;已删除&#39; . $rows . &#39;条数据&#39;;
로그인 후 복사

관련 권장 사항:

javascript 객체 생성, 함수 캡슐화, 속성 코드 예제에 대한 자세한 설명

날짜 함수 및 기능 캡슐화

javascript를 유연하게 사용하여 객체 생성, 함수 캡슐화, 속성 코드 예제 자세한 설명

위 내용은 MySQLI 함수 캡슐화를 기반으로 한 PHP 데이터베이스에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!