Display image from folder usign current user's id from database

Please can someone tell me how I can retrieve ONLY the images for a particular person’s uploaded in the code below?

The below retrieves all images in the uploads folder (name: imagev2Best.php)
PHP Code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">



<head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Welcome to ADesigns: Images</title>

    <link href="css/main.css" rel="stylesheet" type="text/css" />

    <script language="JavaScript">

    <!-- // Hide from old browsers.

    

    // Make a pop-up window function:

    function create_window (image, width, height) {

    

        // Add some pixels to the width and height:

        width = width + 10;

        height = height + 10;

        

        // If the window is already open, 

        // resize it to the new dimensions:

        if (window.popup && !window.popup.closed) {

            window.popup.resizeTo(width, height);

        } 

        

        // Set the window properties:

        var specs = "location=no, scrollbars=no, menubars=no, toolbars=no, resizable=yes, left=0, top=0, width=" + width + ", height=" + height;

        

        // Set the URL:

        var url = "showimagev2Best.php?image=" + image;

        

        // Create the pop-up window:

        popup = window.open(url, "ImageWindow", specs);

        popup.focus();

        

    } // End of function.

    //--></script>

</head>



<body>

<table id="outerTable">

    <tr><td id="logo">

        <div>

            <img src="./images/logo.png" width="150"  height="55"  alt="company_logo" />

        </div>

    </td></tr>

    <tr><td id ="nav">

        <div>

            <a href="home.php">Home</a> |  

            <a href="participate.html">Participate</a> |

            <a href="aboutUs.html">About ADesigns</a> |

            <a href="contact.html">Contact Us</a>

        </div>

    </td></tr>

    <tr><td id="banner"> <! -- page banner image -->

        <img src="images/home.jpg" width="770" height="" alt="welcome to ADesigns">

    </td></tr>

    <tr><td>

        <table id="contentTable">

            <tr>

                <td id="topLeft">

                    <br />

                    <div id="welcomeBox">

                        <h1>Advertisments</h1>

                        <p>This section covers adverts from other companies</p>

                    </div> <! -- mainContent -->

                </td>

                <td id="topRight">

                    <br />

                    <div id="loginRegBox">

                    <h1>Show Images</h1>

                    <p>Click on an image to view it in a separate window.</p>

                    <table align="center" cellspacing="5" cellpadding="5" border="1">

                    <tr>

                        <td align="center"><b>Image Name</b></td>

                        <td align="center"><b>Image Size</b></td>

                    </tr>

                    <?php # Script 10.4 - images.php

                          

                          // This script lists the images in the uploads directory.



                            $dir = 'uploads/'; // Define the directory to view.



                            $files = scandir($dir); // Read all the images into an array.



                            // Display each image caption as a link to the JavaScript function:

                            foreach ($files as $image) {



                            if (substr($image, 0, 1) != '.') { // Ignore anything starting with a period.

    

                            // Get the image's size in pixels:

                            $image_size = getimagesize ("$dir/$image");

        

                            // Calculate the image's size in kilobytes:

                            $file_size = round ( (filesize ("$dir/$image")) / 1024) . "kb";

        

                            // Make the image's name URL-safe:

                            $image = urlencode($image);

        

                            // Print the information:

                        echo "\	<tr>

                            \	\	<td><a href=\\"javascript:create_window('$image',$image_size[0],$image_size[1])\\">$image</a></td>

                            \	\	<td>$file_size</td>

                            \	</tr>\
";

    

                             } // End of the IF.

    

                        } // End of the foreach loop.

                    ?>

                    </table>

                    </div> <! -- mainContentRight -->

            </tr>

            

        </table>

    </td></tr>

    <tr><td  id="footer"><div id="footerLastRow"><p>&copy; ADesigns  &nbsp;&nbsp; <a href="#">Privacy Policy</a> | <a href="#">Terms and Conditions</a></p></div></td></tr>

</table>

</body>

</html>

The code below is used in conjuction with the above to serve up all the imagesname -showimagev2Best.php)

PHP Code:



<?php # Script 10.5 - show_image.php



// This page displays an image.



$name = FALSE; // Flag variable:



// Check for an image name in the URL:

if (isset($_GET['image'])) {



    // Full image path:

    $image = "uploads/{$_GET['image']}";



    // Check that the image exists and is a file:

    if (file_exists ($image) && (is_file($image))) {

    

        // Make sure it has an image's extension:

        $ext = strtolower ( substr ($_GET['image'], -4));

        

        if (($ext == '.jpg') OR ($ext == 'jpeg') OR ($ext == '.png')) {

            // Set the name as this image:

            $name = $_GET['image'];

        } // End of $ext IF.

        

    } // End of file_exists() IF.

    

} // End of isset($_GET['image']) IF.



// If there was a problem, use the default image:

if (!$name) {

    $image = 'uploads/unavailable.png';    

    $name = 'unavailable.png';

}



// Get the image information:

$info = getimagesize($image);

$fs = filesize($image);



// Send the content information:

header ("Content-Type: {$info['mime']}\
");

header ("Content-Disposition: inline; filename=\\"$name\\"\
");

header ("Content-Length: $fs\
");



// Send the file:

readfile ($image);





include('includes/footer.html');

        

?>



The below shows code that stores the images in the uploads folder and database table called imageuploadsv2Best.php)
PHP Code:


 <?php 

 @session_start(); //start session take out and see header error



if (!isset($_SESSION['userID']) )    

 {

    require_once ('loginFunction.inc.php');

    $url = absolute_url();

    header("Location: " .$url);

    exit();

  }     



 $page_title='Welcome to ADesign: Uploads';

 $userID = $_SESSION['userID']; 

 include('includes/header.html');

 

 if (isset($_POST['submitted'])) 

 {    

    // Check for an uploaded file:

    if (isset($_FILES['image'])) 

    {

        // Exit if it is not a logo upload:

        if (!is_uploaded_file($_FILES['image']['tmp_name']))    

            {

                exit('<h1>Not Allowed: Stop</h1><p>There was no logo file uploaded!</p>');

            }

            

            $logoname        =    $_FILES['image']['name'];

            $logotype        =    $_FILES['image']['type'];

        

            //echo '<p>Before jump out</p> ';

        

        // Validate the type. Should be JPEG or PNG.

        $allowed = array ('image/pjpeg', 'image/jpeg', 'image/JPG', 'image/X-PNG', 'image/PNG', 'image/png', 'image/x-png');

        if (in_array($_FILES['image']['type'], $allowed)) 

        {

            //echo '<p>validating image type</p>';

            if (isset($_POST['description'])) 

            {

                //echo '<p>checking radio button</p>';

                $desc = $_POST['description'];

                

                if ($desc = 'logo')

                {    //echo '<p>checking logoradio button</p>';

                    $desc = trim($_POST['description']);

                    

                    // Move the file over.

                    if (move_uploaded_file ($_FILES['image']['tmp_name'], "uploads/{$_FILES['image']['name']}")) 

                    {

                        echo'<h1>Well Done</h1>';

                        echo '<p>The '.$desc. ' file has been uploaded! Follow this link to <a href="imagesv2Best.php">view stored images.</a></p>';

                        

                        require_once('mysql_connect.php');

            

                        $logoInsert = "INSERT INTO image SET 

                                userID = '$userID',

                                filename = '$logoname', 

                                mimetype = '$logotype',

                                description = '$desc'";

                

                        //    Perform the insert.

                        $ok = @mysql_query($logoInsert);

        

                        if(!$ok)

                        {

                            exit('Database error storing file: ' . mysql_error());

                        } // End !ok ...if

                    

                    } // End of move logo... IF.

                    

                    else 

                    { 

                        // Invalid type.

                        echo '<p class="error">Please upload a JPEG or PNG image.</p>';

                    }

                    

                }  // End of logo..IF

                /*

                else if ($desc = 'design')

                {

                    echo'<p>You got to select the design image type';

                    $desc = trim($_POST['description']);

                    // Move the file over.

                    if (move_uploaded_file ($_FILES['image']['tmp_name'], "designs/{$_FILES['image']['name']}")) 

                    {

                        echo'<h1>Well Done</h1>';

                        echo '<p>The design file has been uploaded! Follow this link to <a href="showlogo.php">view the designs</a></p>';

            

            

                        // Store the other logo details in the database:

                        //require_once('mysql_connect.php');

            

                        $designInsert = "INSERT INTO image SET 

                                        userID = '$userID',

                                        filename = '$logoname', 

                                        mimetype = '$logotype',

                                        description = '$desc'";

                

                        //    Perform the insert.

                        $ok = @mysql_query($designInsert);

        

                        if(!$ok)

                        {

                            echo'Error is coming from here design!!';

                            exit('Database error storing file: ' . mysql_error());

                        } // End !ok ...if

                    

                    } // End of move design... IF.

                    

                    else 

                    { 

                        // Invalid type.

                        echo '<p class="error">Please upload a JPEG or PNG image.</p>';

                    }

            

                } // End of design...IF

                

            */

            } // End of description ...IF

            

            else

            {

                echo 'error from your else';

                echo '<h1>Error</h1><p>You did not select an image type</p>';

            }



    } // End of isset($_FILES['logo']) IF.

    

    // Check for an error:

    

    if ($_FILES['image']['error'] > 0) 

    {

        echo '<p class="error">The file could not be uploaded because: <strong>';

    

        // Print a message based upon the error.

        switch ($_FILES['image']['error']) 

        {

            case 1:

                print 'The file exceeds the upload_max_filesize setting in php.ini.';

                break;

            case 2:

                print 'The file exceeds the MAX_FILE_SIZE setting in the HTML form.';

                break;

            case 3:

                print 'The file was only partially uploaded.';

                break;

            case 4:

                print 'No file was uploaded.';

                break;

            case 6:

                print 'No temporary folder was available.';

                break;

            case 7:

                print 'Unable to write to the disk.';

                break;

            case 8:

                print 'File upload stopped.';

                break;

            default:

                print 'A system error occurred.';

                break;

        } // End of switch.

        

        print '</strong></p>';

        

    } // End of error IF.

    

    // Delete the file if it still exists:

    if (file_exists ($_FILES['image']['tmp_name']) && is_file($_FILES['image']['tmp_name']) ) 

    {

        unlink ($_FILES['image']['tmp_name']);

    }

        

        }

} // End of the submitted conditional.



 include('includes/footer.html');

?>

Please I need real help with this. Thanks anyone out THERE
ncax2 is online now Report Post Edit/Delete Message

Get all file names uploaded by a userid from your database (SELECT), store the result in an array, and then inside the foreach (after the scandir) check if the filename exists in the array. If it does, show the filename. If not, ignore it.

Sorry but which of the codes are you referring to and at what point in the code do I write that script please?

Thank you

Sorry do not mean to be annoying but what is the statement for storing the result into an array ?


$filesArray = array();
while ($row = mysql_fetch_assoc($result)) {
    $filesArray[] = $row['filename'];
}

Please correct me if am wrong, based on what you have said I have the following:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Welcome to ADesigns: Images</title>
    <link href="css/main.css" rel="stylesheet" type="text/css" />
    <script language="JavaScript">
	<!-- // Hide from old browsers.
	
	// Make a pop-up window function:
	function create_window (image, width, height) {
	
		// Add some pixels to the width and height:
		width = width + 10;
		height = height + 10;
		
		// If the window is already open, 
		// resize it to the new dimensions:
		if (window.popup && !window.popup.closed) {
			window.popup.resizeTo(width, height);
		} 
		
		// Set the window properties:
		var specs = "location=no, scrollbars=no, menubars=no, toolbars=no, resizable=yes, left=0, top=0, width=" + width + ", height=" + height;
		
		// Set the URL:
		var url = "showimagev2Best.php?image=" + image;
		
		// Create the pop-up window:
		popup = window.open(url, "ImageWindow", specs);
		popup.focus();
		
	} // End of function.
	//--></script>
</head>

<body>
<table id="outerTable">
	<tr><td id="logo">
		<div>
			<img src="./images/logo.png" width="150"  height="55"  alt="company_logo" />
		</div>
	</td></tr>
	<tr><td id ="nav">
		<div>
			<a href="home.php">Home</a> |  
			<a href="participate.html">Participate</a> |
			<a href="aboutUs.html">About ADesigns</a> |
			<a href="contact.html">Contact Us</a>
		</div>
	</td></tr>
	<tr><td id="banner"> <! -- page banner image -->
		<img src="images/home.jpg" width="770" height="" alt="welcome to ADesigns">
	</td></tr>
	<tr><td>
		<table id="contentTable">
			<tr>
				<td id="topLeft">
					<br />
					<div id="welcomeBox">
						<h1>Advertisments</h1>
						<p>This section covers adverts from other companies</p>
					</div> <! -- mainContent -->
				</td>
				<td id="topRight">
					<br />
					<div id="loginRegBox">
					<h1>Show Images</h1>
					<p>Click on an image to view it in a separate window.</p>
					<table align="center" cellspacing="5" cellpadding="5" border="1">
					<tr>
						<td align="center"><b>Image Name</b></td>
						<td align="center"><b>Image Size</b></td>
					</tr>
					<?php # Script 10.4 - images.php
						  
						  // This script lists the images in the uploads directory.

							$dir = 'uploads/'; // Define the directory to view.

							$files = scandir($dir); // Read all the images into an array.

							// Secure connection:
							require_once('mysql_connect');
							$getfilename = "SELECT filename FROM image WHERE userID = '$userID'";
							$result = @mysql_query($getfilename);
							
							$filesArray = array();
							while ($ow = mysql_fetch_assoc($result) )
							{
								$filesArray[] = $row['filename'];
							}

							// Display each image caption as a link to the JavaScript function:
							foreach ($files as $image) 
							{
								// Check if the filename exists in the array $filename
								if($filesArray[] = ($filename) )
								{	
									
									
									if (substr($image, 0, 1) != '.') 
									{ // Ignore anything starting with a period.
	
										// Get the image's size in pixels:
										$image_size = getimagesize ("$dir/$image");
		
										// Calculate the image's size in kilobytes:
										$file_size = round ( (filesize ("$dir/$image")) / 1024) . "kb";
		
										// Make the image's name URL-safe:
										$image = urlencode($image);
		
										// Print the information:
										echo "\	<tr>
												\	\	<td><a href=\\"javascript:create_window('$image',$image_size[0],$image_size[1])\\">$image</a></td>
												\	\	<td>$file_size</td>
											 \	</tr>\
";
	
							 		} // End of the IF.
							 		
							 		else
							 		{
							 			echo'No files match';
							 		}
							 	}
    
							} // End of the foreach loop.
					?>
					</table>
					</div> <! -- mainContentRight -->
			</tr>
			
		</table>
	</td></tr>
	<tr><td  id="footer"><div id="footerLastRow"><p>&copy; ADesigns  &nbsp;&nbsp; <a href="#">Privacy Policy</a> | <a href="#">Terms and Conditions</a></p></div></td></tr>
</table>
</body>
</html>

Is that right?

Where

	require_once('mysql_connect');
							$getfilename = "SELECT filename FROM image WHERE userID = '$userID'";
							$result = @mysql_query($getfilename);
							
							$filesArray = array();
							while ($ow = mysql_fetch_assoc($result) )
							{
								$filesArray[] = $row['filename'];
							}

							// Display each image caption as a link to the JavaScript function:
							foreach ($files as $image) 
							{
								// Check if the filename exists in the array $filename
								if($filesArray[] = ($filename) )
								{	
									
									
									if (substr($image, 0, 1) != '.') 
									{ // Ignore anything starting with a period.
	
										// Get the image's size in pixels:
										$image_size = getimagesize ("$dir/$image");
		
										// Calculate the image's size in kilobytes:
										$file_size = round ( (filesize ("$dir/$image")) / 1024) . "kb";
		
										// Make the image's name URL-safe:
										$image = urlencode($image);
		
										// Print the information:
										echo "\	<tr>
												\	\	<td><a href=\\"javascript:create_window('$image',$image_size[0],$image_size[1])\\">$image</a></td>
												\	\	<td>$file_size</td>
											 \	</tr>\
";
	
							 		} // End of the IF.
							 		
							 		else
							 		{
							 			echo'No files match';
							 		}
							 	}
    
							} // End of the foreach loop.

I made the change here:

[B]// Secure connection:
require_once(‘mysql_connect’);
$getfilename = “SELECT filename FROM image WHERE userID = ‘$userID’”;
$result = @mysql_query($getfilename);

						$filesArray = array();
						while ($ow = mysql_fetch_assoc($result) )
						{
							$filesArray[] = $row['filename'];
						}

						// Display each image caption as a link to the JavaScript function:
						foreach ($files as $image) 
						{
							// Check if the filename exists in the array $filename
							if($filesArray[] = ($filename) )
							{	[/B]

Is that right?

Almost.
This line isn’t correct:


// Check if the filename exists in the array $filename
if($filesArray[] = ($filename) )

Look at this: http://www.php.net/manual/en/function.in-array.php

Also I corrected

require_once('mysql_connection');

to

require_once('mysql_connection.php');

Is that because of the brackets?

No, it’s because that’s not the way to check if a value exists in an array. Did you take a look at the link?

Sorry I just saw it and am looking at the link and trying to implement it now. I will get back to you shortly.

Thanks

Having looked at the link(thanks by the way), I made the following adjustments:

 // This script lists the images in the uploads directory.

							$dir = 'uploads/'; // Define the directory to view.

							$files = scandir($dir); // Read all the images into an array.

							// Secure connection:
							require_once('mysql_connect');
							$getfilename = "SELECT filename FROM image WHERE userID = '$userID'";
							$result = @mysql_query($getfilename);

							$filesArray = array();
							while ($row = mysql_fetch_assoc($result) )
							{
								$filesArray[] = $row['filename'];
							}

							// Display each image caption as a link to the JavaScript function:
							foreach ($files as $image) 
							{
								
								// Check if the filename exists in the array $filename
								if(in_array($files, $filesArray()) )
								{ 
							
									if (substr($image, 0, 1) != '.') 
									{ // Ignore anything starting with a period.
	
										// Get the image's size in pixels:
										$image_size = getimagesize ("$dir/$image");
		
										// Calculate the image's size in kilobytes:
										$file_size = round ( (filesize ("$dir/$image")) / 1024) . "kb";
		
										// Make the image's name URL-safe:
										$image = urlencode($image);
		
										// Print the information:
										echo "\	<tr>
												\	\	<td><a href=\\"javascript:create_window('$image',$image_size[0],$image_size[1])\\">$image</a></td>
												\	\	<td>$file_size</td>
											 \	</tr>\
";
	
							 		} // End of the IF.
							 	
							 	} // End of search within array.
							 	else
							 	{
							 	
							 		echo'file not found';
							 	}
							
							} // End of the foreach loop

and got the an empty table the following:
file not foundfile not foundfile not foundfile not foundfile not foundfile not foundfile not foundfile not foundfile not foundfile not foundfile not foundfile not foundfile not foundfile not foundfile not foundfile not foundfile not foundfile not foundfile not foundfile not found.

And if I take out else{echo’file not found’;}
Please help?

Yes, take out that else.
So none of the files in the directory are present in the array. You didn’t expect that? Try to add some echo (for simple variables) and print_r (for the array) statements to see the values and check if all is ok.

I am a bit of a novice but where in the code do I add the print_r and why am I echoing varibales, what varibles. Please bear with me

First of all, don’t use the @ to suppress error messages, at least not while you’re writing and testing your scripts.
So change


$result = @mysql_query($getfilename);

in


$result = mysql_query($getfilename) or die('mysql error ' . mysql_error() . ' in query ' . $getfilename);

While writing this post, I noticed the error in your script :slight_smile:
You mustn’t confront $files (which is an array) with $filesArray (another array), but $image (which contains a file name) with $filesArray.
So change


// Check if the filename exists in the array $filename
if(in_array($files, $filesArray()) )

in


// Check if the filename exists in the array $filename
if(in_array($image, $filesArray) )

Attention! $filesArray is no function, it’s a variable, so don’t put () after it.

As far as print_r is concerned, you might want to read the manual http://www.php.net/manual/en/function.print-r.php