> 백엔드 개발 > PHP 튜토리얼 > PHP 입문 튜토리얼: Mysqli를 사용하여 데이터베이스를 작동하는 방법(연결, 쿼리, 트랜잭션 롤백 등)

PHP 입문 튜토리얼: Mysqli를 사용하여 데이터베이스를 작동하는 방법(연결, 쿼리, 트랜잭션 롤백 등)

高洛峰
풀어 주다: 2023-03-03 21:48:02
원래의
934명이 탐색했습니다.

이 글의 예제는 PHP 입문 튜토리얼에서 Mysqli를 사용하여 데이터베이스를 운영하는 방법을 설명하고 있습니다. 참고용으로 다음과 같이 모든 사람과 공유하십시오:

Demo1.php

<?php
  //使用 mysqli 对象操作数据库
  //创建 mysqli 对象(资源句柄)
  $_mysqli = new mysqli();
  //连接数据库 1.主机名(ip) 2.账户 3.密码 4.数据库
  //mysqli_connect 函数 == $_mysqli -> connect();
  $_mysqli -> connect(&#39;localhost&#39;,&#39;root&#39;,&#39;123456&#39;,&#39;guest&#39;);
  //断开 MySQL mysqli_close() == $_mysqli -> close();
  $_mysqli -> close();
?>
로그인 후 복사

Demo2.php

<?php
  //不用 connect ,直接使用构造方法
  $_mysqli = new mysqli(&#39;localhost&#39;,&#39;root&#39;,&#39;123456&#39;,&#39;guest&#39;);
  //单独选择一个数据库
  //这里选择的数据库会替代上面的数据库
  //为了避免这些麻烦,尽量不用去单独指向了
  //$_mysqli -> select_db(&#39;school&#39;);
  $_mysqli -> close();
?>
로그인 후 복사

Demo3.php

<?php
  header ( &#39;Content-Type:text/html; charset=utf-8;&#39; );
  //连接 mysql
  //当你参数出现错误,导致连接错误的时候,
  //$_mysqli 这个对象就没有创建成功,也就是说,没有资源句柄的功能
  //就是没有调用 mysqli 下的方法和属性的能力了
  @$_mysqli = new mysqli(&#39;localhost&#39;,&#39;root&#39;,&#39;123456&#39;,&#39;guest&#39;);
  //为什么要用函数去捕捉呢?
  //为什么不用面向对象的方式去捕捉呢?
  if(mysqli_connect_errno()){
    echo &#39;数据库连接出现了错误,错误的信息是:&#39;.mysqli_connect_error();
    exit();
  }
  $_mysqli->close();
?>
로그인 후 복사

Demo4.php

<?php
  header ( &#39;Content-Type:text/html; charset=utf-8;&#39; );
  //连接 mysql
  //当你参数出现错误,导致连接错误的时候,
  //$_mysqli 这个对象就没有创建成功,也就是说,没有资源句柄的功能
  //就是没有调用 mysqli 下的方法和属性的能力了
  @$_mysqli = new mysqli(&#39;localhost&#39;,&#39;root&#39;,&#39;123456&#39;,&#39;guest&#39;);
  //为什么要用函数去捕捉呢?
  //为什么不用面向对象的方式去捕捉呢?
  if(mysqli_connect_errno()){
    echo &#39;数据库连接出现了错误,错误的信息是:&#39;.mysqli_connect_error();
    exit();
  }
  //$_mysqli -> select_db(&#39;fsdfd&#39;);
  //数据库操作时发生的错误
  if($_mysqli -> errno){
    echo &#39;数据库操作错误:&#39;.$_mysqli -> error;
  }
  $_mysqli->close();
?>
로그인 후 복사

Demo5.php

<?php
  header ( &#39;Content-Type:text/html; charset=utf-8;&#39; );
  $_mysqli = new mysqli(&#39;localhost&#39;,&#39;root&#39;,&#39;123456&#39;,&#39;testguest&#39;);
  //数据库连接时发生的错误
  if(mysqli_connect_errno()){
    echo &#39;数据库连接出现了错误,错误的信息是:&#39;.mysqli_connect_error();
    exit();
  }
  //设置一下编码
  $_mysqli -> set_charset(&#39;utf8&#39;);
  //创建一句 SQL ,获取数据库的表的数据
  $_sql = "SELECT * FROM tg_user";
  //执行 SQL 语句,把结果集赋给 $_result
  $_result = $_mysqli -> query($_sql);
  //var_dump($_result); //object(mysqli_result)#2 (0) { }
  //通过结果集,我要取得第一行数据
  //fetch_row();是返回的一个数组,里面是第一条数据的集合
  print_r( $_result -> fetch_row());
  //运行一次,指针下移一条
  print_r( $_result -> fetch_row());
  //销毁结果集
  $_result -> free();
  $_mysqli->close();
?>
로그인 후 복사

Demo6.php

<?php
  header ( &#39;Content-Type:text/html; charset=utf-8;&#39; );
  $_mysqli = new mysqli(&#39;localhost&#39;,&#39;root&#39;,&#39;123456&#39;,&#39;testguest&#39;);
  //数据库连接时发生的错误
  if (mysqli_connect_errno()) {
    echo &#39;数据库连接出现了错误.错误的信息是:&#39;.mysqli_connect_error();
    exit();
  }
  //设置一下编码
  $_mysqli->set_charset(&#39;utf8&#39;);
  //创建一句SQL,获取数据库的表的数据
  $_sql = "SELECT * FROM tg_user";
  //创建一个结果集
  $_result = $_mysqli->query($_sql);
  //使用索引数组取值
  //print_r($_result->fetch_row());
  $_row = $_result->fetch_row();
  echo $_row[3];
  //遍历,下标很难记[3]
  while (!!$_row = $_result->fetch_row()) {
    echo $_row[3].&#39;<br />&#39;;
  }
  $_mysqli->close();
?>
로그인 후 복사

Demo7.php

<?php
  header ( &#39;Content-Type:text/html; charset=utf-8;&#39; );
  $_mysqli = new mysqli(&#39;localhost&#39;,&#39;root&#39;,&#39;123456&#39;,&#39;testguest&#39;);
  //数据库连接时发生的错误
  if (mysqli_connect_errno()) {
    echo &#39;数据库连接出现了错误.错误的信息是:&#39;.mysqli_connect_error();
    exit();
  }
  //设置一下编码
  $_mysqli->set_charset(&#39;utf8&#39;);
  //创建一句SQL,获取数据库的表的数据
  $_sql = "SELECT * FROM tg_user";
  //创建一个结果集
  $_result = $_mysqli->query($_sql);
  //使用关联数组取值
  //print_r($_result->fetch_assoc());
  $_assoc = $_result->fetch_assoc();
  echo $_assoc[&#39;tg_username&#39;];
  //遍历
  while (!!$_assoc = $_result->fetch_assoc()) {
    echo $_assoc[&#39;tg_username&#39;].&#39;<br />&#39;;
  }
  $_mysqli->close();
?>
로그인 후 복사

Demo8.php

<?php
  header ( &#39;Content-Type:text/html; charset=utf-8;&#39; );
  $_mysqli = new mysqli(&#39;localhost&#39;,&#39;root&#39;,&#39;123456&#39;,&#39;testguest&#39;);
  //数据库连接时发生的错误
  if (mysqli_connect_errno()) {
    echo &#39;数据库连接出现了错误.错误的信息是:&#39;.mysqli_connect_error();
    exit();
  }
  //设置一下编码
  $_mysqli->set_charset(&#39;utf8&#39;);
  //创建一句SQL,获取数据库的表的数据
  $_sql = "SELECT * FROM tg_user";
  //创建一个结果集
  $_result = $_mysqli->query($_sql);
  //使用索引+关联数组取值
  //print_r($_result->fetch_array());
  $_array = $_result->fetch_array();
  echo $_array[3];
  echo $_array[&#39;tg_username&#39;];
  //遍历.....
  $_mysqli->close();
?>
로그인 후 복사

Demo9.php

<?php
  header ( &#39;Content-Type:text/html; charset=utf-8;&#39; );
  $_mysqli = new mysqli(&#39;localhost&#39;,&#39;root&#39;,&#39;123456&#39;,&#39;testguest&#39;);
  //数据库连接时发生的错误
  if (mysqli_connect_errno()) {
    echo &#39;数据库连接出现了错误.错误的信息是:&#39;.mysqli_connect_error();
    exit();
  }
  //设置一下编码
  $_mysqli->set_charset(&#39;utf8&#39;);
  //创建一句SQL,获取数据库的表的数据
  $_sql = "SELECT * FROM tg_user";
  //创建一个结果集
  $_result = $_mysqli->query($_sql);
  //使用OOP的方法object
  //print_r($_result->fetch_object());
  echo $_result->fetch_object()->tg_username;
  //使用OOP遍历
  while (!!$_object = $_result->fetch_object()) {
    echo $_object->tg_username.&#39;<br />&#39;;
  }
  $_mysqli->close();
?>
로그인 후 복사

Demo10.php

<?php
  header ( &#39;Content-Type:text/html; charset=utf-8;&#39; );
  $_mysqli = new mysqli(&#39;localhost&#39;,&#39;root&#39;,&#39;123456&#39;,&#39;testguest&#39;);
  //数据库连接时发生的错误
  if (mysqli_connect_errno()) {
    echo &#39;数据库连接出现了错误.错误的信息是:&#39;.mysqli_connect_error();
    exit();
  }
  //设置一下编码
  $_mysqli->set_charset(&#39;utf8&#39;);
  //创建一句SQL,获取数据库的表的数据
  $_sql = "SELECT * FROM tg_user limit 0,10";
  //创建一个结果集
  $_result = $_mysqli->query($_sql);
  //我要看下我选择了多少行
  echo $_result->num_rows;
  //我影响了多少行呢
  echo $_mysqli->affected_rows;
  $_mysqli->close();
?>
로그인 후 복사

Demo11.php

<?php
  header ( &#39;Content-Type:text/html; charset=utf-8;&#39; );
  $_mysqli = new mysqli(&#39;localhost&#39;,&#39;root&#39;,&#39;123456&#39;,&#39;testguest&#39;);
  //数据库连接时发生的错误
  if (mysqli_connect_errno()) {
    echo &#39;数据库连接出现了错误.错误的信息是:&#39;.mysqli_connect_error();
    exit();
  }
  //设置一下编码
  $_mysqli->set_charset(&#39;utf8&#39;);
  //创建一句SQL,获取数据库的表的数据
  $_sql = "UPDATE tg_user SET tg_username=&#39;一站式建网站&#39; WHERE tg_id=5";
  //创建一个结果集
  $_result = $_mysqli->query($_sql);
  //我要看下我选择了多少行
  echo $_result->num_rows;
  echo &#39;|&#39;;
  //我影响了多少行呢
  echo $_mysqli->affected_rows;
  $_mysqli->close();
?>
로그인 후 복사

Demo12.php

<?php
  header ( &#39;Content-Type:text/html; charset=utf-8;&#39; );
  $_mysqli = new mysqli(&#39;localhost&#39;,&#39;root&#39;,&#39;123456&#39;,&#39;testguest&#39;);
  //数据库连接时发生的错误
  if (mysqli_connect_errno()) {
    echo &#39;数据库连接出现了错误.错误的信息是:&#39;.mysqli_connect_error();
    exit();
  }
  //设置一下编码
  $_mysqli->set_charset(&#39;utf8&#39;);
  //创建一句SQL,获取数据库的表的数据
  $_sql = "SELECT * FROM tg_user";
  //创建一个结果集
  $_result = $_mysqli->query($_sql);
  //求出表中有多少个字段
  echo $_result->field_count;
  //获取字段的名字
// $_field = $_result->fetch_field();
// echo $_field->name;
// $_field = $_result->fetch_field();
// echo $_field->name;
//
// while (!!$_field = $_result->fetch_field()) {
//   echo $_field->name.&#39;<br />&#39;;
// }
  //一次性取得所有的字段
  $_fields = $_result->fetch_fields();
  //echo $_fields[0]->name;
  foreach ($_fields as $_field) {
    echo $_field->name.&#39;<br />&#39;;
  }
  $_mysqli->close();
?>
로그인 후 복사

Demo13.php

<?php
  header ( &#39;Content-Type:text/html; charset=utf-8;&#39; );
  $_mysqli = new mysqli(&#39;localhost&#39;,&#39;root&#39;,&#39;123456&#39;,&#39;testguest&#39;);
  //数据库连接时发生的错误
  if (mysqli_connect_errno()) {
    echo &#39;数据库连接出现了错误.错误的信息是:&#39;.mysqli_connect_error();
    exit();
  }
  //设置一下编码
  $_mysqli->set_charset(&#39;utf8&#39;);
  //创建一句SQL,获取数据库的表的数据
  $_sql = "SELECT * FROM tg_user";
  //创建一个结果集
  $_result = $_mysqli->query($_sql);
  //移动数据指针
  $_result->data_seek(9);
  $_row = $_result->fetch_row();
  echo $_row[3];
  //移动字段指针
  $_result->field_seek(3);
  $_field = $_result->fetch_field();
  echo $_field->name;
  $_mysqli->close();
?>
로그인 후 복사

Demo14.php

<?php
  header ( &#39;Content-Type:text/html; charset=utf-8;&#39; );
  $_mysqli = new mysqli(&#39;localhost&#39;,&#39;root&#39;,&#39;123456&#39;,&#39;testguest&#39;);
  //数据库连接时发生的错误
  if (mysqli_connect_errno()) {
    echo &#39;数据库连接出现了错误.错误的信息是:&#39;.mysqli_connect_error();
    exit();
  }
  //设置一下编码
  $_mysqli->set_charset(&#39;utf8&#39;);
  //创建三个修改的SQL语句
  $_sql .= "UPDATE tg_article SET tg_username=&#39;喀喀喀&#39; WHERE tg_id=1;";
  $_sql .= "UPDATE tg_flower SET tg_fromuser=&#39;喀喀喀&#39; WHERE tg_id=1;";
  $_sql .= "UPDATE tg_friend SET tg_fromuser=&#39;喀喀喀&#39; WHERE tg_id=1";
  //使用通知执行的方法
  $_mysqli->multi_query($_sql);
  //普通只能执行sql的方法是:$_mysqli->query($_sql);
  $_mysqli->close();
?>
로그인 후 복사

Demo15.php

<?php
  header ( &#39;Content-Type:text/html; charset=utf-8;&#39; );
  $_mysqli = new mysqli(&#39;localhost&#39;,&#39;root&#39;,&#39;123456&#39;,&#39;testguest&#39;);
  //数据库连接时发生的错误
  if (mysqli_connect_errno()) {
    echo &#39;数据库连接出现了错误.错误的信息是:&#39;.mysqli_connect_error();
    exit();
  }
  //设置一下编码
  $_mysqli->set_charset(&#39;utf8&#39;);
  //创建三条选择语句
  $_sql .= "SELECT * FROM tg_photo;";
  $_sql .= "SELECT * FROM tg_user;";
  $_sql .= "SELECT * FROM tg_friend";
  if ($_mysqli->multi_query($_sql)) {
    //获取当前的结果集
    $_result = $_mysqli->store_result();
    print_r($_result->fetch_row());
    echo &#39;<br />&#39;;
    //将结果集的指针移到下一条
    $_mysqli->next_result();
    $_result = $_mysqli->store_result();
    if (!$_result) {
      echo &#39;第二条SQL语句有五!&#39;;
      exit();
    }
    print_r($_result->fetch_row());
    echo &#39;<br />&#39;;
    $_mysqli->next_result();
    $_result = $_mysqli->store_result();
    if (!$_result) {
      echo &#39;第三条SQL语句有五!&#39;;
      exit();
    }
    print_r($_result->fetch_row());
  } else {
    echo &#39;第一条SQL语句有误&#39;;
    exit();
  }
  $_mysqli->close();
?>
로그인 후 복사

Demo16.php

<?php
  header ( &#39;Content-Type:text/html; charset=utf-8;&#39; );
  $_mysqli = new mysqli(&#39;localhost&#39;,&#39;root&#39;,&#39;123456&#39;,&#39;testguest&#39;);
  //数据库连接时发生的错误
  if (mysqli_connect_errno()) {
    echo &#39;数据库连接出现了错误.错误的信息是:&#39;.mysqli_connect_error();
    exit();
  }
  //设置一下编码
  $_mysqli->set_charset(&#39;utf8&#39;);
  //设置关闭自动提交(手工提交)
  $_mysqli->autocommit(false);
  //创建两个SQL语句
  $_sql .= "UPDATE tg_flower SET tg_flower=tg_flower-50 WHERE tg_id=1;";
  $_sql .= "UPDATE tg_friend SET tg_state=tg_state+50 WHERE tg_id=1";
  //执行多条SQL语句
  //只要这两条SQL语句都成功了,就手工提交给数据库
  //否则,就回滚,撤销之前的有效操作。
  if ($_mysqli->multi_query($_sql)) {
    //通过影响的行数,来判定SQL语句是否成功执行
    //如果$_success是false说明sql语句有吴,那么就执行回滚,否则就手工提交
    $_success = $_mysqli->affected_rows == 1 ? true : false;
    //下移指针
    $_mysqli->next_result();
    $_success2 = $_mysqli->affected_rows == 1 ? true : false;
    //如果两条都成功的话
    if ($_success && $_success2) {
      //执行手工提交
      $_mysqli->commit();
      echo &#39;完美提交&#39;;
    } else {
      //执行回滚,撤销之前的所有操作
      $_mysqli->rollback();
      echo &#39;所有操作归零!&#39;;
    }
  } else {
    echo &#39;第一条SQL语句有错误!&#39;;
  }
  //再开启自动提交
  $_mysqli->autocommit(true);
  $_mysqli->close();
?>
로그인 후 복사

이 글이 PHP 프로그래밍에 종사하는 모든 분들께 도움이 되기를 바랍니다.

Mysqli를 사용하여 데이터베이스를 작동하는 방법(연결, 쿼리, 트랜잭션 롤백 등)에 대한 더 많은 PHP 입문 튜토리얼과 관련 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!

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