Asked  7 Months ago    Answers:  5   Viewed   43 times

I am trying to display the last 5 images uploaded to my "store" table in MySql. I'm a complete noob to PHP and databases and i've been reading a lot on how to do this but no luck.

I can store and display pictures one at a time but i'd like to be able to have a gallery of sorts to show the last 5 uploaded.

any advice or help would be greatly appreciated thanks!

p.s. I know it frowned upon to store pictures to a database like this but this project is just for practice.

index.php

<!DOCTYPE html>
<html>
<head>
<title>Project One</title>
</head>

<body>

<form action="index.php" method="POST" enctype="multipart/form-data">
    File:
    <input type="file" name="image"> <input type="submit" value="Upload">
<form>
<p />

<?php

//connect to database
(connect to server)
(select correct DB)

//file properties
$file = $_FILES['image']['tmp_name'];

if (!isset($file))
    echo "please select an image.";
else
  {
  $image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
  $image_name = $_FILES['image']['name'];
  $image_size = getimagesize($_FILES['image']['tmp_name']); 

  if($image_size==FALSE)
    echo "That's not an image.";
  else
  {
    if (!$insert = mysql_query("INSERT INTO store VALUES ('', '$image_name', '$image')"))
        echo "Problem Uploading Image.";
    else
        {

        $lastid = mysql_insert_id();
        echo "Image uploaded. <p />Your image:<p /><img src=get.php?id=$lastid>";

        }
  }
  }

?>

<p />
<p />
<a href="http://WEBSITE.com/gallery.php"> Go to Gallery </a>
</body>

</html>

get.php

<?php

   //connect to database
    (connect to server)
    (select correct DB)

$id = addslashes($_REQUEST['id']);

$image = mysql_query("SELECT * FROM store WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];

header("Content-type: image/jpeg");

echo $image;

?>

 Answers

72

This is what I used when I wanted to do something like that... a long time ago! =P

$sql = "SELECT image FROM table WHERE cond ORDER BY xxxx DESC LIMIT 5";
$result = mysqli_query($db,$sql);
while($arraySomething = mysqli_fetch_array($result))
{
    echo "<img src='php/imgView.php?imgId=".$arraySomething."' />";
}
Wednesday, March 31, 2021
 
etsous
answered 7 Months ago
85

You should use form method to POST instead of get.

<form action="edit_profile_parse.php" method="post" enctype="multipart/form-data" >
Sunday, June 20, 2021
 
juananrey
answered 5 Months ago
71

From what i understand from your post is that uploading and storing isn't a problem, but showing the images is. That's probably because you're using vars that are not set, so no results kan be found in the database. If i misunderstood let me know.

<?php
// No ID
$image = mysql_query("SELECT * FROM images ORDER BY id DESC");   
?>

Also look at what Prof83 says. Ignore my post if your script works with just one image.

Last but not least, if you're using different filetypes, also echo the correct MIME format in the header.

Update I combined both answers.

Edit your loop:

<?php
while($row = mysql_fetch_assoc($image))
{
        echo '<img src="img.php?id='.$row["id"].'">';
}
?>

Create a page name img.php

<?php
$query = mysql_query("SELECT image FROM images WHERE id = ".$_GET['id']);
$row = mysql_fetch_assoc($query);
header("Content-type: image/jpeg");
echo $row['image'];
?>
Wednesday, July 7, 2021
 
Hat
answered 4 Months ago
Hat
44

Related question:

  • How to retrieve data from Firebase using Javascript?

I only get one result from that database:

c20ej76jhb
45.546058,-122.813203

Using this code (uses on rather than once) with a reference to a database I created with multiple locations (and a different format of data):

var locationsRef = firebase.database().ref("locations");
locationsRef.on('child_added', function(snapshot) {
var data = snapshot.val();
var marker = new google.maps.Marker({
  position: {
    lat: data.lat,
    lng: data.lng
  },
  map: map
});
bounds.extend(marker.getPosition());
marker.addListener('click', (function(data) {
  return function(e) {
    infowindow.setContent(data.name + "<br>" + this.getPosition().toUrlValue(6) + "<br>" + data.message);
    infowindow.open(map, this);
  }
}(data)));
map.fitBounds(bounds);

});

proof of concept fiddle

from your database:

screenshot of resulting map

from mine (with multiple locations and the modified code above):

enter image description here code snippet:

function initialize() {
  var infowindow = new google.maps.InfoWindow();
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  // Initialize Firebase
  var config = {
    apiKey: "AIzaSyC8HcClvIT_FlG8ZwCji4LG-qNx8D9VCrs",
    authDomain: "geocodeziptest.firebaseapp.com",
    databaseURL: "https://geocodeziptest.firebaseio.com",
    projectId: "geocodeziptest",
    storageBucket: "geocodeziptest.appspot.com",
    messagingSenderId: "1096545848604"
  };
  firebase.initializeApp(config);
  //Create a node at firebase location to add locations as child keys
  var locationsRef = firebase.database().ref("locations");
  var bounds = new google.maps.LatLngBounds();
  locationsRef.on('child_added', function(snapshot) {
    var data = snapshot.val();
    console.log(data);
    var marker = new google.maps.Marker({
      position: {
        lat: data.lat,
        lng: data.lng
      },
      map: map
    });
    bounds.extend(marker.getPosition());
    marker.addListener('click', (function(data) {
      return function(e) {
        infowindow.setContent(data.name + "<br>" + this.getPosition().toUrlValue(6) + "<br>" + data.message);
        infowindow.open(map, this);
      }
    }(data)));
    map.fitBounds(bounds);
  });
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.1/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/geofire/4.1.2/geofire.min.js"></script>
<div id="map_canvas"></div>
Friday, August 6, 2021
 
seaders
answered 3 Months ago
19

It depends on what is more important to you: speed, ease of access, ...

If you have an application in which you have to bind conceptually a picture to a record (eg. contacts application) i would go the dbms way. It may be not that fast (something which is very subjective) but it is much easier to handle.

It is also much simpler to store pics in a dbms if you want to back up your data! (consider the fact you have to issue only ONE backup command and you have backed up ALL your data).

I suspect that you have somehow to store other data which is bound to pictures. If this holds true than i would definitely go the dbms way. If this should not be true than don't bother designing a schema, create the dbms, create connections, store data,.... to much overhead!

Saturday, August 7, 2021
 
lewiguez
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :