skip to Main Content

Im currently in the process of creating a simple PHP website which can display a list of NBA teams and the respective players. One of the things I’m currently working on right now is adding the ability to upload images from the page itself instead of going to PHPMyAdmin.

Here’s what the page looks like right now:

enter image description here

I’m trying to figure out how to add the team logo the same way I can add a new team name. As you can see in the bottom part there is an Add Team option which allows the user to add a new team and that team will be registered in the database.

I’ve tried to write some PHP code which enables the process of uploading images but have failed to do so.

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>

And this is the add_team.php file, which gets the data from database

<?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 how the standing.php page looks like

enter image description here

updated 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

Answers


  1. You have to first upload successfully to the folder then you can add record in to your database

    <?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.";
    }
    }
    
    ?>
    

    Your HTML should be

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

    Refer https://github.com/aslamanver/nbaTest

    Login or Signup to reply.
  2. You should create a uniqid when uploading the image, this way depending on how many people will upload images, if one were to upload the same image as another, it wouldn’t be overwritten in the database

    You can do this by using the explode and end function in PHP, also look into prepared statements when using SQL statements, this is to protect your DB against SQL injections, here’s a good link:
    https://www.w3schools.com/php/php_mysql_prepared_statements.asp

    The $_FILES has a few attributes including $_FILES["name"]["error"] which checks for errors, ideally you would make an if statement in which you specify the error condition for the file to uploaded to your DB. Also remember that you must first specify the directory before inserting it into your DB and if the file containing the code is in another folder, you use ../ to go back a directory.

    When you display the image on your site you use this:
    <img src="directory/<?php echo $row["row"]; ?>">

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search