在PHP页面中上传图片

时间:2019-02-24 18:58:20

标签: php mysql

我目前正在创建一个简单的PHP网站,该网站可以显示NBA球队和各个球员的名单。我当前正在处理的事情之一是添加了从页面本身上传图像的功能,而不是使用PHPMyAdmin。

这是当前页面的外观:

enter image description here

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

我尝试编写一些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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

上传图像时,您应该创建一个uniqid,这种方式取决于要上传图像的人数,如果一个人要与另一个图像上载相同的图像,则该图像不会在数据库中被覆盖

您可以通过使用PHP中的explodeend函数来执行此操作,还可以在使用SQL语句时查看准备好的语句,这是为了保护您的数据库免受SQL注入,这是一个很好的链接: https://www.w3schools.com/php/php_mysql_prepared_statements.asp

$_FILES具有一些属性,其中包括$_FILES["name"]["error"],用于检查错误,理想情况下,您可以执行if语句,在其中指定要上传到数据库的文件的错误条件。还要记住,必须先指定目录,然后才能将其插入数据库,如果包含代码的文件在另一个文件夹中,则可以使用../返回目录。

当您在网站上显示图像时,请使用以下命令: <img src="directory/<?php echo $row["row"]; ?>">