Home Backend Development PHP Problem How to implement music list in php

How to implement music list in php

Nov 01, 2021 am 10:06 AM
php

How to implement music list in php: 1. Read the content from the file and decode it; 2. Display the data in the list, and use foreach to display the data one by one in the list.

How to implement music list in php

The operating environment of this article: Windows7 system, PHP7.1 version, DELL G3 computer

How does php implement a music list?

PHP implements uploading, displaying and deleting music lists:

##Ideas list.php list display
1. Read the content from the file and decode it

$json = file_get_contents('data.json');$songs = json_decode($json, true);
Copy after login
2. Display the data in the list and use foreach to The data is displayed one by one in the list

<?php foreach ($songs as $item): ?>
        <tr>
          <td class="align-middle"><?php echo $item[&#39;title&#39;]; ?></td>
        </tr><?php endforeach ?>
Copy after login
add.php

1. Submit the form to its own web page for processing
2. Give each input box a name value
3. PHP processing At this time, you can process the data through $_POST['title']
4. After processing, save the data to the file/database

<form action="<?php echo $_SERVER[&#39;PHP_SELF&#39;]; ?>" method="post" enctype="multipart/form-data"><label for="title">标题</label>
        <input type="text" class="form-control " id="title" name="title"> <button class="btn btn-primary btn-block">保存</button></form>
Copy after login
// 读取已有数据
  $songs = json_decode(file_get_contents('data.json'), true);
  // 追加新数据
  $songs[] = $new_song;
  // 将追加的结果写入文件
  file_put_contents('data.json', json_encode($songs));
Copy after login
del.php

1. If you need to delete it, you must Provide who you want to delete and get the ID to be deleted
Here, you can determine which one to delete by reading the $item['id'] value from the file/database at the beginning. Also remove button a label? The following is the value that can be transmitted to the background

 <a class="btn btn-outline-danger btn-sm" href="del.php?id=<?php echo $item[&#39;id&#39;]; ?>">删除</a>
Copy after login
2. Read data from the database/file

3. Find the corresponding key to be deleted in the data through the ID, and put the data back into the file after deletion /Database

Source code del.php

<?php// 只要有人请求我 del.php 我就执行删除操作// 如果需要我执行删除就必须提供你想要删除的是谁// 一般情况下如果客户端需要给服务端提供简单的数据标识,// 这种情况都会采用URL 地址传递问号参数的方式传递// 校验(客户端来的东西都不能信)if (empty($_GET['id'])) {
  exit('你必须提供要删除的数据ID'); // exit 会直接结束脚本的运行}// 确保客户端提交了 ID$id = $_GET['id'];// 1. 读取已有数据$json = file_get_contents('data.json');// 2. 反序列化$songs = json_decode($json, true);// 3. 遍历数组找到要删除的元素foreach ($songs as $item) {
  if ($item['id'] === $id) {
    // 找到了要删除的数据
    // 4. 在数组中删除这个元素
    // 4.1. 找到这个数据在数组的下标
    $index = array_search($item, $songs);
    array_splice($songs, $index, 1);
    // 5. 将删除过后的数组序列化成 JSON 字符串
    $new_json = json_encode($songs);
    // 6. 持久化
    file_put_contents('data.json', $new_json);
    break;
  }}// 跳转回去header('Location: /songs/list.php');
Copy after login
add.php

<?php

function receive_form () {
  // global $error_type;
  // 1. 校验客户端提交的数据
  // 1.1. 校验标题
  // empty($_POST[&#39;title&#39;]) === !(isset($_POST[&#39;title&#39;]) && $_POST[&#39;title&#39;] !== &#39;&#39;)
  // empty函数的作用就是判断一个成员是否为空(未定义、值为false)
  if (empty($_POST[&#39;title&#39;])) {
    // 标题未正常填写
    $GLOBALS[&#39;error_type&#39;] = &#39;title&#39;;
    $GLOBALS[&#39;error_msg&#39;] = "填写标题";
    return;
  }

  if (empty($_POST[&#39;artist&#39;])) {
    // 歌手未正常填写
    $GLOBALS[&#39;error_type&#39;] = &#39;artist&#39;;
    $GLOBALS[&#39;error_msg&#39;] = "填写歌手";
    return;
  }

  // ===================================================

  // echo "校验文件";
  // 校验上传文件
  //  1. 校验是否上传成功(error)
  if ($_FILES[&#39;source&#39;][&#39;error&#39;] !== UPLOAD_ERR_OK) {
    $GLOBALS[&#39;error_type&#39;] = &#39;source&#39;;
    $GLOBALS[&#39;error_msg&#39;] = "上传失败";
    return;
  }

  //  2. 校验上传文件的类型(type)
  $allowed_source_types = array(&#39;audio/mp3&#39;, &#39;audio/wma&#39;);
  if (!in_array($_FILES[&#39;source&#39;][&#39;type&#39;], $allowed_source_types)) {
    $GLOBALS[&#39;error_type&#39;] = &#39;source&#39;;
    $GLOBALS[&#39;error_msg&#39;] = "只能上传音频文件";
    return;
  }

  //  3. 校验文件大小(size)文件的大小单位是字节
  if (1 * 1024 * 1024 > $_FILES[&#39;source&#39;][&#39;size&#39;] || $_FILES[&#39;source&#39;][&#39;size&#39;] > 10 * 1024 * 1024) {
    $GLOBALS[&#39;error_type&#39;] = &#39;source&#39;;
    $GLOBALS[&#39;error_msg&#39;] = "上传文件大小不合理";
    return;
  }

  //  将文件从临时目录中移动到网站下面
  $tmp_path = $_FILES[&#39;source&#39;][&#39;tmp_name&#39;]; // 临时路径
  $dest_path = &#39;../uploads/mp3/&#39; . $_FILES[&#39;source&#39;][&#39;name&#39;]; // 存放路径
  $source = substr($dest_path, 2);
  $moved = move_uploaded_file($tmp_path, $dest_path); // 返回移动是否成功

  if (!$moved) {
    $GLOBALS[&#39;error_type&#39;] = &#39;source&#39;;
    $GLOBALS[&#39;error_msg&#39;] = "上传失败";
    return;
  }

  // ============= 处理多个文件逻辑 ====================

  // 如果一个文件域是多文件上传的话,文件域的 name 应该是由 [] 结尾
  for ($i = 0; $i < count($_FILES[&#39;images&#39;][&#39;error&#39;]); $i++) {
    // 1. 校验上传成功
    if ($_FILES[&#39;images&#39;][&#39;error&#39;][$i] !== UPLOAD_ERR_OK) {
      $GLOBALS[&#39;error_type&#39;] = &#39;images&#39;;
      $GLOBALS[&#39;error_msg&#39;] = "上传图片失败";
      return;
    }
    // 2. 校验文件类型
    $allowed_images_types = array(&#39;image/jpeg&#39;, &#39;image/png&#39;, &#39;image/gif&#39;);
    if (!in_array($_FILES[&#39;images&#39;][&#39;type&#39;][$i], $allowed_images_types)) {
      $GLOBALS[&#39;error_type&#39;] = &#39;images&#39;;
      $GLOBALS[&#39;error_msg&#39;] = "只能上传图片文件";
      return;
    }
    // 3. 校验大小
    if ($_FILES[&#39;images&#39;][&#39;size&#39;][$i] > 1 * 1024 * 1024) {
      $GLOBALS[&#39;error_type&#39;] = &#39;images&#39;;
      $GLOBALS[&#39;error_msg&#39;] = "上传文件大小不合理";
      return;
    }
    // 移动文件
    $img_tmp_path = $_FILES[&#39;images&#39;][&#39;tmp_name&#39;][$i]; // 临时路径
    $img_dest_path = &#39;../uploads/img/&#39; . $_FILES[&#39;images&#39;][&#39;name&#39;][$i]; // 存放路径
    $img_moved = move_uploaded_file($img_tmp_path, $img_dest_path); // 返回移动是否成功
    if (!$img_moved) {
      $GLOBALS[&#39;error_type&#39;] = &#39;images&#39;;
      $GLOBALS[&#39;error_msg&#39;] = "上传图片失败";
      return;
    }

    $images[] = substr($img_dest_path, 2);
  }

  // 2. 保存数据
  $new_song = array(
    &#39;id&#39; => uniqid(), // uniqid 获取一个唯一ID
    &#39;title&#39; => $_POST[&#39;title&#39;],
    &#39;artist&#39; => $_POST[&#39;artist&#39;],
    &#39;images&#39; => $images,
    &#39;source&#39; => $source
  );
  // 读取已有数据
  $songs = json_decode(file_get_contents(&#39;data.json&#39;), true);
  // 追加新数据
  $songs[] = $new_song;
  // 将追加的结果写入文件
  file_put_contents(&#39;data.json&#39;, json_encode($songs));

  // 3. 响应
  header(&#39;Location: /songs/list.php&#39;);
}

if ($_SERVER[&#39;REQUEST_METHOD&#39;] === &#39;POST&#39;) {
  // 处理接收校验表单
  receive_form();
}

?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>添加新音乐</title>
  <link rel="stylesheet" href="bootstrap.css">
</head>
<body>
  <div class="container py-5">
    <h1>添加新音乐</h1>
    <hr>
    <form action="<?php echo $_SERVER[&#39;PHP_SELF&#39;]; ?>" method="post" enctype="multipart/form-data">
      <div>
        <label for="title">标题</label>
        <input type="text" class="form-control <?php echo isset($error_type) && $error_type === &#39;title&#39; ? &#39;is-invalid&#39; : &#39;&#39;; ?>" id="title" name="title" value="<?php echo isset($_POST[&#39;title&#39;]) ? $_POST[&#39;title&#39;] : &#39;&#39;; ?>">
        <small><?php echo $error_msg; ?></small>
      </div>
      <div>
        <label for="artist">歌手</label>
        <input type="text" class="form-control <?php echo isset($error_type) && $error_type === &#39;artist&#39; ? &#39;is-invalid&#39; : &#39;&#39;; ?>" id="artist" name="artist" value="<?php echo isset($_POST[&#39;artist&#39;]) ? $_POST[&#39;artist&#39;] : &#39;&#39;; ?>">
        <small><?php echo $error_msg; ?></small>
      </div>
      <div>
        <label for="images">海报</label>
        <!-- multiple 可以让文件域多选 -->
        <!-- accept 可以指定文件域能够选择的默认文件类型 MIME Type -->
        <!-- image/* 代表所有类型图片 -->
        <!-- 除了使用 MIME 类型 还可以使用文件后缀名限制:.png,.jpg -->
        <input type="file" id="images" name="images[]" multiple accept="image/*">
      </div>
      <div>
        <label for="source">音乐</label>
        <input type="file" class="form-control <?php echo isset($error_type) && $error_type === &#39;source&#39; ? &#39;is-invalid&#39; : &#39;&#39;; ?>" id="source" name="source" accept="audio/*">
        <small><?php echo $error_msg; ?></small>
      </div>
      <button class="btn btn-primary btn-block">保存</button>
    </form>
  </div>
</body>
</html>
Copy after login

list.php

<?php

// 1. 读取文件内容
$json = file_get_contents(&#39;data.json&#39;);
// 2. 反序列化
// json_decode 第二个参数可以用来指定返回数据都采用 关联数组的方式 描述对象
$songs = json_decode($json, true);
// 3. 遍历数据渲染HTML
// var_dump($songs);

?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>音乐列表</title>
  <link rel="stylesheet" href="bootstrap.css">
</head>
<body>
  <div class="container py-5">
    <h1>音乐列表</h1>
    <hr>
    <div class="px-2 mb-3">
      <a href="add.php" class="btn btn-secondary btn-sm">添加</a>
    </div>
    <table class="table table-bordered table-striped table-hover">
      <thead>
        <tr>
          <th><input type="checkbox" name="" id=""></th>
          <th>标题</th>
          <th>歌手</th>
          <th>海报</th>
          <th>音乐</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($songs as $item): ?>
        <tr>
          <td><input type="checkbox" name="" id=""></td>
          <td><?php echo $item[&#39;title&#39;]; ?></td>
          <td><?php echo $item[&#39;artist&#39;]; ?></td>
          <td>
            <?php foreach ($item[&#39;images&#39;] as $img): ?>
            <img src="<?php echo $img; ?>" alt="">
            <?php endforeach ?>
          </td>
          <td><audio src="<?php echo $item[&#39;source&#39;]; ?>" controls></audio></td>
          <td>
            <a class="btn btn-outline-danger btn-sm" href="del.php?id=<?php echo $item[&#39;id&#39;]; ?>">删除</a>
            <!-- hidden 隐藏域 -->
            <!-- <form action="del.php" method="get">
              <input type="hidden" name="id" value="<?php echo $item[&#39;id&#39;]; ?>">
              <button class="btn btn-danger btn-sm">删除</button>
            </form> -->
          </td>
        </tr>
        <?php endforeach ?>
      </tbody>
    </table>
  </div>
</body>
</html>
Copy after login

Recommended Study: "

PHP Video Tutorial"

The above is the detailed content of How to implement music list in php. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles