php - 在PHP页面上传图片

标签 php mysql

我目前正在创建一个简单的 PHP 网站,可以显示 NBA 球队和各自球员的列表。我目前正在做的事情之一是添加从页面本身上传图像的功能,而不是转到 PHPMyAdmin。

这是页面现在的样子:

enter image description here

我正在尝试弄清楚如何添加团队 Logo ,就像添加新的团队名称一样。正如您在底部看到的,有一个“添加团队”选项,允许用户添加新团队,并且该团队将在数据库中注册。

我尝试编写一些 PHP 代码来实现上传图像的过程,但未能成功。

team_list.php

<?php
error_reporting(0);

    require_once('../Model/database.php');

    // Get all categories
    $query = 'SELECT * FROM categories
              ORDER BY categoryID';
    $statement = $db->prepare($query);
    $statement->execute();
    $teams = $statement->fetchAll();
    $statement->closeCursor();

 // Initialize message variable
 $msg = "";

 // If upload button is clicked ...
 if (isset($_POST['upload'])) {
   // Get image name
   $image = $_FILES['image'];

   // image file directory
   $target = "images/".basename($image);

   $sql = "INSERT INTO categories (img) VALUES ('$image')";
   // execute query
   mysqli_query($db, $sql);

   if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
     $msg = "Image uploaded successfully";
   }else{
     $msg = "Failed to upload image";
   }
 }
 $result = mysqli_query($db, "SELECT * FROM categories");
?>
<!DOCTYPE html>
<html>

<!-- the head section -->
<head>
    <title>NBA</title>
    <link rel="stylesheet" type="text/css" href="../css/index.css">
    <link rel="shortcut icon" type="image/png" href="images/favicon.ico"/>

</head>

<!-- the body section -->

<body>
    <main>
    <h1 id="addCategoryh1">Teams</h1>
    <table id="categoryListTable">
        <tr>
            <th>Name</th>
            <th>&nbsp;</th>
        </tr>
        <?php foreach ($teams as $team) : ?>
        <tr>
            <td><?php echo $team['categoryName']; ?></td>
            <td>
                <form action="delete_team.php" method="post"
                      id="delete_product_form">
                    <input type="hidden" name="team_id"
                           value="<?php echo $team['categoryID']; ?>">
                    <input id="deleteCategoryList" type="submit" value="Delete">
                </form>

            </td>
        </tr>
        <?php endforeach; ?>
    </table>
    <br>

    <?php
    while ($row = mysqli_fetch_array($result)) {
      echo "<div id='img_div'>";
        echo "<img src='images/".$row['image']."' >";
        echo "<p>".$row['image_text']."</p>";
      echo "</div>";
    }
  ?>

    <h2 id="add_category_h2">Add Team</h2>
    <form action="add_team.php" method="post"
          id="add_category_form">

        <label>Name:</label>
        <input type="input" name="name">
        <input id="add_category_button" type="submit" value="Add">
    </form>

    <form method="POST" action="team_list.php" enctype="multipart/form-data">
    <input type="hidden" name="size" value="1000000">
    <div>
      <input type="file" name="image">
    </div>
    <div>
        <button type="submit" name="upload">POST</button>
    </div>
  </form>

    <br>
    <p><a href="../index.php">View Team List</a></p>

    </main>
    <footer id="categoryListFooter">
        <p>&copy; <?php echo date("Y"); ?> NBA</p>
    </footer>
</body>
</html>

这是 add_team.php 文件,它从数据库获取数据

<?php
// Get the team data
$name = filter_input(INPUT_POST, 'name');

// Validate inputs
if ($name == null) {
    $error = "Invalid team data. Check all fields and try again.";
    include('../Error/error.php');
} else {
    require_once('../Model/database.php');

    // Add the product to the database
    $query = 'INSERT INTO categories (categoryName)
              VALUES (:team_name)';

    $query = "INSERT INTO categories (image) VALUES ('$fileName', '$content')";

    $statement = $db->prepare($query);
    $statement->bindValue(':team_name', $name);
    $statement->execute();
    $statement->closeCursor();

    // Display the team List page
    include('team_list.php');
}
?>

这就是standing.php页面的样子

enter image description here

更新了 add_team.php

// Get the team data
$name = filter_input(INPUT_POST, 'name');

// Validate inputs
if ($name == null) {
    $error = "Invalid team data. Check all fields and try again.";
    include('../Error/error.php');
} else {
    require_once('../Model/database.php');


    // Add the product to the database
    $query = 'INSERT INTO categories (categoryName)
              VALUES (:team_name)';

    $query = "INSERT INTO categories (image) VALUES ('$fileName', '$content')";

    $statement = $db->prepare($query);
    $statement->bindValue(':team_name', $name);
    $statement->execute();
    $statement->closeCursor();

    // Display the team List page
    include('team_list.php');

    // This is the directory where images will be saved
    $target = "../images/";
    $target = $target . basename( $_FILES['image']['name']);

    // This gets all the other information from the form
    $filename = basename( $_FILES['image']['name']);
    $team_name = $_POST['team_name'];


    // Write the file name to the server
    if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {

    //Tells you if its all ok
    echo "The file ". basename( $_FILES['image']['name']). " has been uploaded, and your information has been added to the directory";

    // Connects to your Database
    mysql_connect("renwid", "password") or die(mysql_error()) ;
    mysql_select_db("nba") or die(mysql_error()) ;

    //Writes the information to the database
    mysql_query("INSERT INTO categories (img, team_name)
    VALUES ('$filename', '$team_name')") ;

} else {
    //Gives and error if its not
    echo "Sorry, there was a problem uploading your file.";
}
}
?>

enter image description here

最佳答案

您必须先成功上传到文件夹,然后才能将记录添加到数据库中

<?php

if(isset($_POST['submit'])) {

// This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['image']['name']);

// This gets all the other information from the form
$filename = basename( $_FILES['image']['name']);
$team_name = $_POST['team_name'];


// Write the file name to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {

    //Tells you if its all ok
    echo "The file ". basename( $_FILES['image']['name']). " has been uploaded, and your information has been added to the directory";

    // Connects to your Database
    // mysql_connect("localhost", "root", "") or die(mysql_error()) ;
    // mysql_select_db("your_db") or die(mysql_error()) ;

    //Writes the information to the database
    // mysql_query("INSERT INTO picture (image, team_name)
    // VALUES ('$filename', '$team_name')") ;

} else {
    //Gives and error if its not
    echo "Sorry, there was a problem uploading your file.";
}
}

?>

您的 HTML 应该是

<form action="" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="image" id="image">
    <input type="text" name="team_name" id="team_name">
    <input type="submit" value="Submit" name="submit">
</form>

引用https://github.com/aslamanver/nbaTest

关于php - 在PHP页面上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54855385/

相关文章:

javascript - onclick,删除未定义

php - 偏离起始标记头,在此上下文中不允许元素样式作为元素主体的子元素。 (抑制来自该子树的更多错误。)

mysql - 使用 Knex 通过 Waterline/Sails 进行迁移

javascript - 在响应式 HTML 中向 PHP 表单添加验证

php - 在 PHP 中创建多语言网页

php - 格式化用 PHP 创建的 XML 文档 - DOMDocument

php - 项目未导入到 CRUD 数据库应用程序,并且无法检索值

php - MySQL 从 pdo lastInsertID 中获取 0

php - 如果已输入数据,如何填充多页表单;如果没有当前数据,如何将其留空?

php - 如何在 Laravel 中实现组合的交叉连接和内连接?