Home Backend Development PHP Tutorial Basic skills in PHP+MariaDB database operation

Basic skills in PHP+MariaDB database operation

Jun 22, 2018 pm 05:16 PM
mariadb php operate database

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

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;;
}
Copy after login

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

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

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

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

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

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

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

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

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 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

See all articles