Home Backend Development PHP Tutorial PHP method to implement database addition, deletion, modification and query

PHP method to implement database addition, deletion, modification and query

May 25, 2018 pm 02:08 PM
php database method

This article introduces to you the methods and sample codes for connecting to the database with PHP and implementing the add, delete, modify and query functions of the database. I hope it will be helpful for everyone to learn PHP

1. Query :

Data display, here you can embed php for data output


<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>无标题文档</title>
</head>

<body>
<table width="100%" border="1" cellpadding="0" cellspacing="0">
  <tr>
    <td>代号</td>
    <td>名称</td>
    <td>性别</td>
    <td>生日</td>
    <td>班级</td>
    <td>操作</td>
  </tr>

<?php
$db = new MySQLi("localhost","root","12345678","heiheihei");
//连接数据库
$sql = "select * from student ";
//写sql语句
$r = $db->query($sql);
//执行sql语句返回给r
if($r)//条件
{
  while ($attr = $r->fetch_row())
  {
    $ssex = "";
     if($attr[2])
     {
       $ssex = "男";
     }
     else
       {
         $ssex = "女";
       }
    echo
    "
 <tr>
    <td>{$attr[0]}</td>
    <td>{$attr[1]}</td>
    <td>{$ssex}</td>
    <td>{$attr[3]}</td>
    <td>{$attr[4]}</td>
//添加一个单击事件,防止不小心删掉
<td><a onclick=\"return confirm(&#39;确定要删除吗???&#39;)" 
href=&#39;shanchu.php?sno={$attr[0]}&#39;>删除</a>
 <a href=&#39;xiugai.php?sno={$attr[0]}&#39;>修改</a> </td> </tr>"; } } ?>

 
 

</table>
<a href="tianjia.php" rel="external nofollow" >添加页面</a>
</body>

</html>
Copy after login

2. Deletion processing page

When deleting, it is linked to the deletion processing page, so a deletion processing page must be written:


<?php
$aaa = $_GET ["sno"]; //删除方式使用的get,照旧
$db = new mysqli("localhost","root","12345678","heiheihei");
//连接...
$sql = "delete from student WHERE sno=&#39;{$aaa}&#39;";
//写sql语句,sno主键
if($db->query($sql)) //执行sql语句
{
  header("location:text.php");
//删完回去表页面
}
else{
  echo "删除失败";
}
?>
Copy after login


Here is a rendering:

3 .Add data:

Click to enter the add page

Add page:


<body>

<h1>添加</h1>
<form action="add.php" method="post" >
  <p>代号:<input type="text" name="sno"/></p>
  <p>名字:<input type="text" name="sname"/></p>
  <p>性别: <input type="radio" value="1" name="sex" />男
    <input type="radio" value="0" name="sex"/>女</p>
  <p>日期:<input type="text" name="sbirthday"/></p>
//创建表时性别是用的1或2来表示的,要是进行修改不知道1或2代表了什么,所以就要进行处理,处理成用户能够明白的男和女

  <p>班级:
  <select name="class">

  <?php
    $db= new MYSQLi("localhost","root","12345678","heiheihei");
//连接...
    $sql = " select * from class ";
//写sql...    

    $r = $db->query($sql);
//执行...返回...
    while($arr = $r->fetch_row())
    {
      echo "<option value=&#39;{$arr[0]}&#39;>{$arr[1]}</option>";
      //添上以后回表页面
    }
    ?>

 
  </select>
  </p>
  <p><input type="submit" value="添加"/></p>
</form>

</body>
Copy after login

Adding also requires a processing page to determine the addition:


<?php
$sno = $_POST["sno"];
//$_POST 变量用于收集来自 method="post" 的表单中的值。
$sname = $_POST["sname"];
$ssex = $_POST["ssex"];
$sbirthday = $_POST["sbirthday"];
$class = $_POST["class"];
$db = new mysqli("localhost","root","12345678","heiheihei");
$sql = "insert into student VALUES (&#39;{$sno}&#39;,&#39;{$sname}&#39;,&#39;{$ssex}&#39;,&#39;{$sbirthday}&#39;,&#39;{$class}&#39;)";
//向数据库中添加写的数据
  if($db->query($sql))
{
  header("location:text.php");
  //header() 函数向客户端发送原始的 HTTP 报头。
}
else {
  echo "添加失败";
}


?>
Copy after login


##Rendering:

4. Modify data: The primary key cannot be modified! !


##
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>无标题文档</title>
</head>

<body>

<h1>修改</h1>

<?php
$sno = $_GET{"sno"};
$db = new mysqli("localhost","root","12345678","heiheihei");
$sql = "select * from student WHERE sno=&#39;{$sno}&#39;";
$r = $db->query($sql);
$arr = $r->fetch_row();
?>

 
<form action="update.php" method="post">
  <p>代号:<input readonly="readonly" type="text" name="sno" value="<?php
echo $arr[0];
?>"/></p>

//readonly只可读
 <p>名称:<input type="text" name="sname" value="<?php echo $arr[1]; ?>"/></p> <p>性别: <input type="radio" name="ssex" value="1" <?php echo $arr[2]?"checked=&#39;checked&#39;":""; ?>/>男 <!-- 三元运算符,如果性别=ture,默认值就在男上面,否则空--> <input type="radio" name="ssex" value="0" <?php echo $arr[2]?"":"checked=&#39;checked&#39;"; ?>/>女 </p> <p>日期:<input type="text" name="sbirthday" value="<?php echo $arr[3]; ?>"/></p> <p>班级:<select name="class">
//value取默认值
 

 <?php
      $sclass = "select * from class";
      $rclass = $db->query($sclass);
      while($attr = $rclass->fetch_row())
      //取到的班级信息
      {
        //判断将要输出的班级是不是和该人员的是否相同
        if($arr[4]==$attr[0])//arr是班级名,attr是班级的代号,俩表
        {
          echo "<option value = &#39;{$attr[0]}&#39; selected=&#39;selected&#39;>{$attr[1]}</option>";

        }
        else{
          echo "<option value = &#39;{$attr[0]}&#39;>{$attr[1]}</option>";
        }

      }
      ?>

 
    </select></p>
  <p><input type="submit" value="修改完毕"/></p>

</form>


</body>
</html>
Copy after login

]

Modified processing page:


<?php
$sno = $_POST["sno"];
$sname = $_POST["sname"];
$ssex = $_POST["ssex"];
$sbirthday = $_POST["sbirthday"];
$class = $_POST["class"];
$db = new mysqli("localhost","root","12345678","heiheihei");
$sql = "update student set sname=&#39;{$sname}&#39;,
ssex=&#39;{$ssex}&#39;,
sbirthday=&#39;{$sbirthday}&#39;,
class=&#39;{$class}&#39; WHERE sno=&#39;{$sno}&#39;";
//看一下是不是传递过来的sno值;
if($db->query($sql))
{
  header("location:text.php");
}
else{
  echo "修改失败";
}



?>
Copy after login

Modified renderings:

The above is the entire content of this article, I hope it will be helpful to Everyone’s learning helps.


Related recommendations:

How to implement

add, delete, modify, check operations on xml using PHP

PHP is based on the object-oriented mysqli extension library

Add, delete, modify and checkMethods of operating tool classes
##PDO to mysql database

Add, delete, modify and check

Detailed explanation of operation steps

##

The above is the detailed content of PHP method to implement database addition, deletion, modification and query. 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

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,

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

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

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.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

See all articles