search
HomeBackend DevelopmentPHP TutorialBasic skills in PHP+MariaDB database operation
Basic skills in PHP+MariaDB database operationJun 22, 2018 pm 05:16 PM
mariadbphpoperatedatabase

This article mainly introduces the basic skills of PHP MariaDB database operation. It summarizes and analyzes PHP MariaDB database connection, judgment, and related operation implementation skills and precautions based on PHP MariaDB such as user login, management, and deletion based on PHP MariaDB. It is necessary to Friends can refer to

The examples in this article summarize the basic skills of PHP MariaDB database operation. I share it with you for your reference. The details are as follows:

PHP MySQL is a relatively common combination. Since I subjectively don’t like Oracle very much, and after MySQL was acquired by Oracle, some changes have occurred in my bones, so I changed it. MariaDB, a brother who still adheres to MySQL's original open source belief. They are essentially the core of MySQL, so all the following database operation codes can be used directly in MySQL.

After setting up the basic environment of PHP Apache and installing the MySQL database at night, I wrote the simplest database connection code, and the result was the following classic error: Fatal error: Class 'mysqli' not found

<?php
  $db = new mysqli(&#39;localhost&#39;, &#39;root&#39;, &#39;admin&#39;, &#39;test&#39;);
  if (mysqli_connect_errno())
  {
    echo &#39;<p>&#39; . &#39;Connect DB error&#39;;
    exit;
  }
?>

In fact, this problem is relatively simple. From the error returned by the PHP engine, we know that mysqli has not been loaded correctly. Most of the problems are This happened in the configuration of the php.ini file. The default semicolon in front of the configuration item "extension=php_mysqli.dll" was not removed. I didn't make this mistake. There is also the file php_mysqli.dll in the ext directory in the PHP installation path. So where did the problem occur? The problem should still occur in the wrong place in the php.ini file. After some reading, I found that "extension_dir = "ext"" has not been modified. I didn't think much about it at the time, thinking that the PHP engine could automatically find this relative path. But then I thought about it, the PHP engine is loaded by Apache, and Apache does not know this relative relationship. Or honestly change this place to an absolute path, and it's OK. In fact, you can write this piece of code before this code to see if the mysqli component has been loaded. This method is suitable for pre-loading judgment of other components.

if (extension_loaded(&#39;mysqli&#39;))
{
  echo &#39;yes&#39;;
}
else
{
  echo &#39;no&#39;;
}

The following uses a user registration and system login to record the most basic operation method of PHP MySQL.

1. Create database, tables and users.

DROP DATABASE IF EXISTS `test`;
CREATE DATABASE `test`
USE `test`;
DROP TABLE IF EXISTS `tbl_user`;
CREATE TABLE `tbl_user` (
 `username` varchar(32) NOT NULL default &#39;&#39;,
 `password` varchar(32) NOT NULL default &#39;&#39;,
 PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;

2. Create registration and login html pages, which are register.html and login.html respectively. As shown in the figure below:

3. Registration and login code:

register_do.php

<?php
  $username = $_POST[&#39;username&#39;];
  $password = $_POST[&#39;password&#39;];
  $db = new mysqli(&#39;localhost&#39;, &#39;root&#39;, &#39;admin&#39;, &#39;test&#39;);
  if (mysqli_connect_errno())
  {
    echo &#39;<p>&#39; . &#39;Connect DB error&#39;;
    exit;
  }
  $query = "select * from tbl_user where username = &#39;" . $username . "&#39;";
  echo &#39;<p>&#39; . $query;
  $result = $db->query($query);
  if ($result)
  {
    echo &#39;<p>&#39; . &#39;The user &#39;. $username .&#39; exist&#39;;
    echo &#39;<p>&#39; . &#39;<a href="register.html" rel="external nofollow" rel="external nofollow" >Back to register</a>&#39;;
  }
  else
  {
    $query = "insert into tbl_user values (&#39;". $username ."&#39;, &#39;". $password ."&#39;)";
    echo &#39;<p>&#39; . $query;
    $result = $db->query($query);
    if ($result)
    {
      echo &#39;<p>&#39; . &#39;<a href="register.html" rel="external nofollow" rel="external nofollow" >Register successful</a>&#39;;
    }
  }
?>

login_do.php

<?php
  $username = $_POST[&#39;username&#39;];
  $password = $_POST[&#39;password&#39;];
  $db = new mysqli(&#39;localhost&#39;, &#39;root&#39;, &#39;admin&#39;, &#39;test&#39;);
  if (mysqli_connect_errno())
  {
    echo &#39;<p>&#39; . &#39;Connect DB error&#39;;
    exit;
  }
  $query = "select * from tbl_user where username = &#39;" . $username . "&#39; and password = &#39;" . $password . "&#39;";
  echo &#39;<p>&#39; . $query;
  $result = $db->query($query);
  if ($result->num_rows)
  {
    echo &#39;<p>&#39; . &#39;<a href="login.html" rel="external nofollow" rel="external nofollow" >Login successful</a>&#39;;
  }
  else
  {
    echo &#39;<p>&#39; . &#39;<a href="login.html" rel="external nofollow" rel="external nofollow" >Login failed</a>&#39;;
  }
?>

userlist.php

<?php
  $db = new mysqli(&#39;localhost&#39;, &#39;root&#39;, &#39;admin&#39;, &#39;test&#39;);
  if (mysqli_connect_errno())
  {
    echo &#39;<p>&#39; . &#39;Connect DB error&#39;;
    exit;
  }
  echo &#39;<p>&#39; . &#39;All user as follows:&#39;;
  $query = "select * from tbl_user order by username";
  if ($result = $db->query($query))
  {
    while ($row = $result->fetch_assoc())
    {
      echo &#39;<p>&#39; . &#39;Username : &#39; . $row[&#39;username&#39;] . &#39;  <a href="userdelete.php?username=&#39; . $row[&#39;username&#39;] . &#39;" rel="external nofollow" >delete</a>&#39;;
    }
  }
?>

4. The final display effect of the page is as shown below:

5. The code to delete the user:

userdelete.php

<?php
  $username = $_GET[&#39;username&#39;];
  $db = new mysqli(&#39;localhost&#39;, &#39;root&#39;, &#39;admin&#39;, &#39;test&#39;);
  if (mysqli_connect_errno())
  {
    echo &#39;<p>&#39; . &#39;Connect DB error&#39;;
    exit;
  }
  $query = "delete from tbl_user where username = &#39;" . $username . "&#39;";
  echo $query;
  if ($result = $db->query($query))
  {
    echo &#39;<p>&#39; . &#39;Delete user &#39; . $username . &#39; successful&#39;;
  }
  else
  {
    echo &#39;<p>&#39; . &#39;Delete user &#39; . $username . &#39; failed&#39;;
  }
  echo &#39;<p>&#39; . &#39;<a href="userlist.php" rel="external nofollow" >Back to user list</a>&#39;;
?>

Prepare preprocessing

1. The book adding page is as shown below (bookadd.html):

2. The table creation script is as follows:

DROP DATABASE IF EXISTS `test`;
CREATE DATABASE IF NOT EXISTS `test`;
USE `test`;
DROP TABLE IF EXISTS `tbl_book`;
CREATE TABLE IF NOT EXISTS `tbl_book` (
 `isbn` varchar(32) NOT NULL,
 `title` varchar(32) NOT NULL,
 `author` varchar(32) NOT NULL,
 `price` float NOT NULL,
 PRIMARY KEY (`isbn`)
) ENGINE=InnoDB DEFAULT CHARSET=utf-8;

3. The added logic processing code is as follows (bookadd_do.php ): What needs special attention here is the sentence "$db->query("set names utf-8")", which means that when writing data to the database, utf-8 encoding and decoding is used. Displays the encoding and decoding settings for database table operations to prevent Chinese garbled characters. I will record an article specifically on this technical point later.

<?php
  $isbn = $_POST[&#39;isbn&#39;];
  $title = $_POST[&#39;title&#39;];
  $author = $_POST[&#39;author&#39;];
  $price = $_POST[&#39;price&#39;];
  $db = new mysqli(&#39;localhost&#39;, &#39;root&#39;, &#39;admin&#39;, &#39;test&#39;);
  if (mysqli_connect_errno())
  {
    echo &#39;<p>&#39; . &#39;Connect DB error&#39;;
    exit;
  }
  $db->query("set names utf-8"); //特别注意这句话
  $stmt = $db->stmt_init();
  $stmt->prepare("insert into tbl_book values (?,?,?,?)");
  $stmt->bind_param("sssd", $isbn, $title, $author, $price);
  $stmt->execute();
  echo &#39;<p>&#39; . &#39;Affect rows is &#39; . $stmt->affected_rows;
  echo &#39;<p>&#39; . &#39;<a href="booklist.php" rel="external nofollow" >Go to book list page</a>&#39;;
?>

4. The logic code for displaying book information is as follows. Also pay attention to the sentence "$db->query("set names utf- 8")":

<?php
  $db = new mysqli(&#39;localhost&#39;, &#39;root&#39;, &#39;admin&#39;, &#39;test&#39;);
  if (mysqli_connect_errno())
  {
    echo &#39;<p>&#39; . &#39;Connect DB error&#39;;
    exit;
  }
  $db->query("set names utf-8"); //特别注意这句话
  $stmt = $db->stmt_init();
  $stmt->prepare("select * from tbl_book");
  $stmt->bind_result($isbn, $title, $author, $price);
  $stmt->execute();
  while($stmt->fetch())
  {
    echo &#39;ISBN : &#39; . $isbn . &#39;<p>&#39;;
    echo &#39;Title : &#39; . $title . &#39;<p>&#39;;
    echo &#39;Author : &#39; . $author . &#39;<p>&#39;;
    echo &#39;Price : &#39; . $price . &#39;<p>&#39;;
    echo &#39;<p>&#39; . &#39;-----------------------------&#39; . &#39;<p>&#39;;
  }
?>

5. The displayed page is as shown below:

##Okay, the most basic part is recorded here. The PHP engine provides very convenient database operation methods, but development is by no means so simple. Various exceptions must be carefully considered how to catch and how to handle them. Database design is also a very interesting topic.

Articles you may be interested in:

PHP database operation class based on pdo

Contents related to mysql read-write separation implemented by PHP

PHP implements the method of compressing multiple files into zip format and downloading them locally

The above is the detailed content of Basic skills in PHP+MariaDB database operation. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft