Home Backend Development PHP Tutorial PHP introductory tutorial: How to use Mysqli to operate the database (connection, query, transaction rollback, etc.)

PHP introductory tutorial: How to use Mysqli to operate the database (connection, query, transaction rollback, etc.)

Dec 22, 2016 am 11:47 AM

The example in this article describes the method of using Mysqli to operate the database in the PHP introductory tutorial. Share it with everyone for your reference, the details are as follows:

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();
?>
Copy after login

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();
?>
Copy after login

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();
?>
Copy after login

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();
?>
Copy after login

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();
?>
Copy after login

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();
?>
Copy after login

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();
?>
Copy after login

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();
?>
Copy after login

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();
?>
Copy after login

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();
?>
Copy after login

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();
?>
Copy after login

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();
?>
Copy after login

Demo 13.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();
?>
Copy after login

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();
?>
Copy after login

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();
?>
Copy after login

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();
?>
Copy after login

I hope this article will be helpful to everyone in PHP program design.

For more PHP introductory tutorials on how to use Mysqli to operate the database (connection, query, transaction rollback, etc.) and related articles, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles