Jump to content

Upload image code example


Html

Recommended Posts

<?php
# Access session.
session_start() ;

# Redirect if not logged in.
if ( !isset( $_SESSION[ 'user_id' ] ) ) { require ( 'login_tools.php' ) ; load() ; }

  // Create database connection
  $dbc = mysqli_connect("", "", "", "");

  // Initialize message variable
  $msg = "";

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

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

  	$sql = "INSERT INTO images (image, image_text) VALUES ('$image', '$image_text')";
  	// execute query
  	mysqli_query($dbc, $sql);

  	if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
  		$msg = "Image uploaded successfully";
  	}else{
  		$msg = "Failed to upload image";
  	}
  }
  $result = mysqli_query($dbc, "SELECT * FROM images");
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
<style type="text/css">
   #content{
   	width: 50%;
   	margin: 20px auto;
   	border: 1px solid #cbcbcb;
   }
   form{
   	width: 50%;
   	margin: 20px auto;
   }
   form div{
   	margin-top: 5px;
   }
   #img_div{
   	width: 80%;
   	padding: 5px;
   	margin: 15px auto;
   	border: 1px solid #cbcbcb;
   }
   #img_div:after{
   	content: "";
   	display: block;
   	clear: both;
   }
   img{
   	float: left;
   	margin: 5px;
   	width: 300px;
   	height: 140px;
   }
</style>
</head>
<body>
<div id="content">
  <?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>";
    }
  ?>
  <form method="POST" action="upload.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>
</div>
</body>
</html>

I got this upload an image code from here, I have tinkered it so it works, I just need to get it be personal for a user, and display the uploaded image at a particular page.

https://codewithawa.com/posts/image-upload-using-php-and-mysql-database

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

 $_SESSION[ 'user_id' ]

This particular code I want to display on the home.php page. I need to tuck in a $_session

 

Thanks.

Link to comment
Share on other sites

Yes, not sure where, I tried the obvious above for the display of the image, but that won't work in the php code checker.

Currently it just uploads an image, stores in the db, and displays on the same page as the code displays. So for it to be a particular user, session id is required especially for the display code.

I did try it, but it didn't work, that is without the $_session.

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

$result = mysqli_query($dbc, "SELECT * FROM images");

This below is where the display begins.

https://www.php.net/manual/en/function.msql-fetch-array.php

while ($row msql_fetch_array($resultMSQL_ASSOC)) {
    echo 
$row['id'] . ': ' $row['name'] . "\n";

Edited by Html
Added code line. Link
Link to comment
Share on other sites

The idea would be for a logged in user to be able upload a image then save the image file name to that user id row in a column for that image. Then you can retrieve that specific image to that specific user. You also might want to add timestamp to filename to prevent duplicate image filenames being saved, meaning a user could get someone elses image.

Link to comment
Share on other sites

So add image and image_text to the users table?

Hmm, as for the id, how does that work out with the code above?

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

while ($row msql_fetch_array($resultMSQL_ASSOC)) {
    echo 
$row['id'] . ': ' $row['name'] . "\n";

Is this above required for the code from the image code?

<?php
   while ($row msql_fetch_array($resultMSQL_ASSOC)) {
    echo 
$row['id'] . ': ' $row['image']  : $row['image_text'] . "\n";

      echo "<div id='img_div'>";
          echo "<img src='images/".$row['image']."' >";
          echo "<p>".$row['image_text']."</p>";
      echo "</div>";
    }
  ?>

 

Edited by Html
code edit
Link to comment
Share on other sites

53 minutes ago, Html said:

<?php
   while ($row msql_fetch_array($resultMSQL_ASSOC)) {
    echo 
$row['id'] . ': ' $row['image']  : $row['image_text'] . "\n";

      echo "<div id='img_div'>";
          echo "<img src='images/".$row['image']."' >";
           echo "<p>".$row['image_text']."</p>";
       echo "</div>";
    }
  ?>

This seems fine, but has errors in it. Check the first echo after row image, missing dot and single quote or delete the line. As you asked the first echo is not required, was probably used to show you the results.

Link to comment
Share on other sites

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

Keep it like this, I thought the example was necessary for an id add in.

 

Link to comment
Share on other sites

8 hours ago, Html said:

So add image and image_text to the users table?

 Hmm, as for the id, how does that work out with the code above? 

When the image has been successfully uploaded use update to update at very least image filename, and text to respective columns where user id equals session user id.

Link to comment
Share on other sites

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

There is only id for the images table, so user_id won't work like I have placed it above? Since user_id is on the users table.

Edited by Html
Link to comment
Share on other sites

OK! Probably going to regret asking this, but here goes, Please! Tell me that the userid with images within images table, matches the specific user userid within user table.🙏🤞🤞

IF if they match you would match userid from both tables to bring up the image/s specfic to user in user table.

Edited by dsonesuk
Link to comment
Share on other sites

Well, are you getting at they must be linked somehow, here is an image, I'm not giving enough info on what I have.

All I did was do what the page has stated.

 

Untitled.jpg

Edited by Html
Link to comment
Share on other sites

Like i said you need userid to be saved to image table, so they have to be logged in to get userid from session.

Then you retrieve user table info and image table info together WHERE userid from user table equals userid from image table. That is what will link them both together.

Link to comment
Share on other sites

Instead of id, user_id? Keep both.

echo ".$row['user_id']."'";

This alone will link them? it will connect with it. I am going to need to type some code for this?

, 'you retrieve user table and image table together where user_id equals userid or user_id? from the image table '

Link to comment
Share on other sites

It doesn't matter what you name them as long as both match each other as identifier value reference  for a specific user. You then use select query to select column names from both tables where one user id ref value would equal the other users id ref value.

Try it! add userid to image table with values equaling those in users table, and try to bring up data from both where id ref match.

Link to comment
Share on other sites

CREATE TABLE IF NOT EXISTS images (
user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
image VARCHAR(100) NOT NULL,
image_text text NOT NULL,
reg_date DATETIME NOT NULL,
PRIMARY KEY (user_id)
);

I decided to create the table this way, so user_id is consistent. The other way I couldn't really get it edited, and working. So may be this is a little better.

As for values, what exactly, this is the image table, and the user table is obviously different, in values, so I don't quite understand what you mean by adding the same values, only user_id is currently the same in both tables now. As well reg_date, not that important, I guess?

Edited by Html
Link to comment
Share on other sites

Each user will have a unique number right! For example In user table

User tom userid #1

User mick userid  #2

User harry userid #3

 Image table

Userid #1 image_a.jpg

Userid #1 image_b.jpg

Userid #2 image_c.jpg

Userid #3 image_d.jpg

Userid #3 image_e.jpg

Userid #3 image_f.jpg

User tom id 1 has 2 images in image table

User id mick 2 has 1 image in image table

User harry id 3 has 3 images in image table

By using userid from session in SQL statement in WHERE usertablename.userid=$user_id AND imagetablename.userid =$user_id

You can bring up data for instance "tom" along with images saved under his id number image_a.jpg and image_b.jpg

That is what we call a relational database, the id are keys to other related information stored on different tables. The user table stores 1 row of data related to specific user id, the image table could be as i have done in my example, a table that stores many rows of images to specific user, this is known as a one to many relationship.

NOTE: You would not use auto-increment for userid for image table because you HAVE to enter the id number on inserting/updating to image table.

Edited by dsonesuk
Link to comment
Share on other sites

11 hours ago, Html said:

CREATE TABLE IF NOT EXISTS images (
user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
image VARCHAR(100) NOT NULL,
image_text text NOT NULL,
reg_date DATETIME NOT NULL,
PRIMARY KEY (user_id)
);

You don't want to use Auto increment in user_id on images table (as mentioned above), instead just get the value from $_SESSION. You are also setting it as Primary key, which means you can't have multiple images linked to one person. (However if you do, just use unique and create id column for images table with Auto_increment+Primary key.

Edited by Mudsaf
Link to comment
Share on other sites

I remove the auto increment setting for images table.

So, this sql statement will fit into this code. This below is wrong,

$sql = "SELECT FROM images WHERE user_id images.userid=$user_id AND imagetablename.userid =$user_id ";
<?php
   while ($row = msql_fetch_array($result, MSQL_ASSOC))
      echo "<div id='img_div'>";
        echo ".$row['user_id']."'";
          echo "<img src='images/".$row['image']."' >";
           echo "<p>".$row['image_text']."'</p>";
       echo "</div>";
    }
  ?> 
Edited by Html
Link to comment
Share on other sites

You should go through the SQL tutorial, there are tons of example of SELECT queries. This is very basic SQL, if you cannot spot the syntax errors then you're missing the most basic knowledge of SQL.

We've gone through this before in other threads, you can't just take code from somewhere else and make random edits in the hopes that it will work. You need to understand the language you're working with.

I am not even going to get into the SQL injection vulnerabilities in your code, but that is something you should do some reading on as well if you don't want your website to be hacked.

Link to comment
Share on other sites

Hmm, the reason I began searching these examples is because I couldn't go further with just learning the language.

I do have the SQL in easy steps book, but I don't it covers quite what I am doing. It is all to do with just editing in the actual sql db, not using it in php for web pages.

That code alone has vulnerability? Where about is it, and it is easy to patch up?

Link to comment
Share on other sites

It's somewhat easy to patch up, but you need to know what to do (how php and sql works). I'd suggest you to learn about check out these links if you want to have more secure system against SQL injections.

https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection

and

https://www.w3schools.com/php/php_mysql_prepared_statements.asp

---

On 11/22/2019 at 2:27 AM, Html said:

$sql = "INSERT INTO images (image, image_text) VALUES ('$image', '$image_text')";

I'd also recommend to sanitize or escape the image name too from $image.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...