School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 306,975 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,869 people online right now. Registration is fast and FREE... Join Now!




Uploading Images with PHP

 
Reply to this topicStart new topic

> Uploading Images with PHP, Build the next Flickr! (DICr???)

Rating  5
akozlik
Group Icon



post 10 Dec, 2008 - 11:41 AM
Post #1


There have been a lot of posts in the PHP forum regarding how to upload files to a server and put them into a database. A lot of people were trying to put the entire binary file into the database, which was the incorrect way to do things. This tutorial is an attempt to explain how to properly upload images to your website, and store their records in the database using PHP and MySQL.

Please note that this tutorial has a lot of code. The code is well commented and will explain much of what we're trying to do. I'll give an overview in the tutorial, but you need to dig into the code to really understand how things work. Also, please note that this tutorial assumes you know some basics of PHP and MySQL and dont' have any problems writing and reading to and from a database.

The first thing we'll do is build a database. I have created a simple database named 'people', which will hold first and last names of people, as well as a picture of them. You can copy and paste this SQL statement into phpMyAdmin to build your table.

sql

CREATE TABLE `people` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`fname` VARCHAR( 30 ) NOT NULL ,
`lname` VARCHAR( 40 ) NOT NULL ,
`filename` VARCHAR( 50 ) NOT NULL
) ENGINE = MYISAM ;


Next, we will build our directory structure. We have our root folder which will hold all our directories, as well as our PHP files. Within this root directory we have a directory named 'images' and another named 'includes'. When we finish we will have a structure that looks like this

CODE

root-directory/images.php
root-directory/index.php
root-directory/upload.php
root-directory/images/
root-directory/includes/conn.php


Within the includes/conn.php file, you should paste this code:

php

<?php

// Input your information for the database here

// Host name
$host = "localhost";

// Database username
$username = "username";

// Database password
$password = "password";

// Name of database
$database = "db_name";

$conn = mysql_connect($host, $username, $password) or die ("Could not connect");
$db = mysql_select_db($database, $conn) or die ("Could not select DB");

?>


On any page that connects to the database, you will require() this file. Be sure to save that file as conn.php within the includes folder.

Next we build our index file. For us, this will just be a form with three fields. One will be 'fname', one will be 'lname', and the next will be a file upload named 'image'. Please note I did some basic CSS styling, but if you don't want to style it that's fine.

php

<?php
// Start a session for displaying any form errors
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Dream in code tutorial</title>

<style type="text/css">
label
{
float: left;
text-align: right;
margin-right: 10px;
width: 100px;
color: black;
}

#submit
{
float: left;
margin-top: 5px;
position: relative;
left: 110px;
}

#error
{
color: red;
font-weight: bold;
font-size: 16pt;
}
</style>
</head>

<body>

<div>
<?php
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p>
<label>First Name</label>
<input type="text" name="fname" /><br />

<label>Last Name</label>
<input type="text" name="lname" /><br />

<label>Upload Image</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input type="submit" id="submit" value="Upload" />
</p>
</form>
</div>
</body>
</html>


Make sure you notice that we are starting a session at the very top of the page. This will be handy for reporting any errors we have with the form. In addition, we have some code before the form to display any errors that are encountered. After displaying the error message we unset the error session variable.

Another thing to note is the MAX_FILE_SIZE. This can be used to ensure that the filesize of the file uploaded is less than that variable. I've left you on your own to write that portion of the script, but I promise you it is not hard.

Save that file as index.html in your root directory.


Now comes the important part. Here is the entire source file with comments. I will briefly go over how it works, but the details are within the source code:

php

<?php
// Start a session for error reporting
session_start();

// Call our connection file
require("includes/conn.php");

// Check to see if the type of file uploaded is a valid image type
function is_valid_type($file)
{
// This is an array that holds all the valid image MIME types
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif");

if (in_array($file['type'], $valid_types))
return 1;
return 0;
}

// Just a short function that prints out the contents of an array in a manner that's easy to read
// I used this function during debugging but it serves no purpose at run time for this example
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}

// Set some constants

// This variable is the path to the image folder where all the images are going to be stored
// Note that there is a trailing forward slash
$TARGET_PATH = "images/";

// Get our POSTed variables
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$image = $_FILES['image'];

// Sanitize our inputs
$fname = mysql_real_escape_string($fname);
$lname = mysql_real_escape_string($lname);
$image['name'] = mysql_real_escape_string($image['name']);

// Build our target path full string. This is where the file will be moved do
// i.e. images/picture.jpg
$TARGET_PATH .= $image['name'];

// Make sure all the fields from the form have inputs
if ( $fname == "" || $lname == "" || $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: index.php");
exit;
}

// Check to make sure that our file is actually an image
// You check the file type instead of the extension because the extension can easily be faked
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: index.php");
exit;
}

// Here we check to see if a file with that name already exists
// You could get past filename problems by appending a timestamp to the filename and then continuing
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: index.php");
exit;
}

// Lets attempt to move the file from its temporary directory to its new home
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
// NOTE: This is where a lot of people make mistakes.
// We are *not* putting the image into the database; we are putting a reference to the file's location on the server
$sql = "insert into people (fname, lname, filename) values ('$fname', '$lname', '" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
header("Location: images.php");
exit;
}
else
{
// A common cause of file moving failures is because of bad permissions on the directory attempting to be written to
// Make sure you chmod the directory to be writeable
$_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory";
header("Location: index.php");
exit;
}
?>


Alright, so we start out by starting a session and requiring our conn.php file. Nothing new there.

Next, we have a function that checks to see if the upload file is of a valid type. This function helps deter people from uploading exe files, as well as other potentially harmful stuff you don't want on your server. We have a variable that holds all the valid MIME types. That list is by no means exhaustive, but it works for our purposes. For a full list of MIME types check out the Webmaster Tookit's list

The next function is just something I use for debugging. This prints the contents of an array so that it's readable.

We create a constant variable that will hold our target path. I didn't use the define() function, but I could have.

Next block of code checks to make sure none of the fields were blank. This is just very basic form validation and can be adjusted for what you see fit.

The next block makes a call to the is_valid_type function and checks to make sure that the file is valid.

The next block of code checks to see if a file of that name already exists, in an effort to keep people from overwriting files. A good way to ensure a unique filename is to parse out the name part of the file name before the period, append a timestamp, and then hash it. After hashing it, add the extension back on. I'm attempting to keep this tutorial simple, so I did not show that, but you should be able to figure that out. Just use substrings.

Finally, we attempt to move the uploaded file to the new directory. Make sure the new directory has proper write permissions, or your script won't be able to save.

If moving the file was successful, we input the information into the database. Make sure you notice that we do not input the binary file into the database. What we have done is moved the file to a directory where we can access it, and then stored the images file name into the database. Whenever we want to print out the image we get its file name from the database and then build the img tag.


Lastly, we have our images.php page, which will display all those great images you've uploaded.

php

<?php
// Get our database connector
require("includes/conn.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Dream in code tutorial - List of Images</title>
</head>

<body>

<div>

<?php
// Grab the data from our people table
$sql = "select * from people";
$result = mysql_query($sql) or die ("Could not access DB: " . mysql_error());

while ($row = mysql_fetch_assoc($result))
{
echo "<div class=\"picture\">";
echo "<p>";

// Note that we are building our src string using the filename from the database
echo "<img src=\"images/" . $row['filename'] . "\" alt=\"\" /><br />";
echo $row['fname'] . " " . $row['lname'] . "<br />";
echo "</p>";
echo "</div>";
}

?>

</div>
</body>
</html>


There's really nothing there that you shouldn't be able to understand.

Well, that's all I have for you! Now you know how to properly upload images to a website and store their references into the database. You get two thumbs up icon_up.gif icon_up.gif .

If you've found this tutorial useful, or if you have any comments let me know! Good luck!
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

Moonbat
Group Icon



post 16 Dec, 2008 - 06:12 PM
Post #2
I'm glad you brought up the whole "references" thing. I can't beleive how many people have thought of trying to store the image itself in the DB. This'll be a great help for newbies (hey, it was for me! biggrin.gif)
Go to the top of the page
+Quote Post

Robsphp
*



post 10 Jan, 2009 - 04:13 PM
Post #3
akozlik

THANK YOU, I am trying to add to my members database an option to have there own avi file then grab it out of the database and display it.

Would I use the same idea (upload the avi's into a directory then reference them in the users table) ?

regards

Rob
Go to the top of the page
+Quote Post

akozlik
Group Icon



post 10 Jan, 2009 - 05:56 PM
Post #4
QUOTE(Robsphp @ 10 Jan, 2009 - 07:13 PM) *

akozlik

THANK YOU, I am trying to add to my members database an option to have there own avi file then grab it out of the database and display it.

Would I use the same idea (upload the avi's into a directory then reference them in the users table) ?

regards

Rob



Yeah the idea's the same. I'm not sure how to best handle partially streamed videos or anything like that, but you can get the party started by using the same idea.

Hope that helps.
Go to the top of the page
+Quote Post

Robsphp
*



post 11 Jan, 2009 - 01:07 PM
Post #5
Akozlik

I get the following error ?

Warning: Cannot modify header information - headers already sent by (output started at /public_html/test/includes/conn.php:10) in /public_html/test/upload.php on line 81

When i try the images.php it seems to have worked but I get that error when upload.php is used ????

Rob
Go to the top of the page
+Quote Post

teampoop
Group Icon



post 11 Jan, 2009 - 09:49 PM
Post #6
You have to have your header() calls before you do any output to the browser. So if your code has an echo (or print) before your header call, you will get an error. This is probably why there was a session variable set, to pass the information to the redirected page.

ex:
CODE

<?php
echo "checking for stuff";
header("Location: index.php"); // ERROR ensues
?>


Hope this helps.

QUOTE(Robsphp @ 11 Jan, 2009 - 01:07 PM) *

Akozlik

I get the following error ?

Warning: Cannot modify header information - headers already sent by (output started at /public_html/test/includes/conn.php:10) in /public_html/test/upload.php on line 81

When i try the images.php it seems to have worked but I get that error when upload.php is used ????

Rob

Go to the top of the page
+Quote Post

Robsphp
*



post 12 Jan, 2009 - 02:01 AM
Post #7
Still not working ?

So does the session variable have to be cleared ?

Is the code wrong ?

regards

Rob





QUOTE(teampoop @ 11 Jan, 2009 - 09:49 PM) *

You have to have your header() calls before you do any output to the browser. So if your code has an echo (or print) before your header call, you will get an error. This is probably why there was a session variable set, to pass the information to the redirected page.

ex:
CODE

<?php
echo "checking for stuff";
header("Location: index.php"); // ERROR ensues
?>


Hope this helps.

QUOTE(Robsphp @ 11 Jan, 2009 - 01:07 PM) *

Akozlik

I get the following error ?

Warning: Cannot modify header information - headers already sent by (output started at /public_html/test/includes/conn.php:10) in /public_html/test/upload.php on line 81

When i try the images.php it seems to have worked but I get that error when upload.php is used ????

Rob


Go to the top of the page
+Quote Post

akozlik
Group Icon



post 12 Jan, 2009 - 11:16 AM
Post #8
The session variable does not need to be cleared.

Are you printing anything before you redirect? That includes any html tags, spaces, whatever. If you send anything to the browser, your header won't be sent.

If you start a thread in the PHP Forum and post your code, we can take a look. I'd like to keep comments on here specifically focused on the tutorials themselves. Each individual case can be handled in the thread.

Thanks and glad you like the tut!
Go to the top of the page
+Quote Post

goodmuyis
*



post 24 Feb, 2009 - 01:55 AM
Post #9
HelLo Mr, thanks for this stuff is just for me
but am trying to change the file size but it doesn't respond to my changes, the size is it in byte or Kb(am sorry for that)

and thanks for ur stuff once again
Go to the top of the page
+Quote Post

chingkit
*



post 9 May, 2009 - 08:23 AM
Post #10
Hi,reading this tutorial really caught my attention. I am now working on my personal website, and planning to add my own photo gallery..I try to experiment with the code you have given and I find it so cool and easy to understood to a newbie like me. I Just like ask for one part of the tutorial, because I'm a bit confused. How can I create the directory.. Is it the folder which I'll be using to store all of my php files?..something like this.

root-directory/images.php
root-directory/index.php
root-directory/upload.php
root-directory/images/
root-directory/includes/conn.php

Hoping for your reply.Thanks in Advance=)

This post has been edited by chingkit: 9 May, 2009 - 08:50 AM
Go to the top of the page
+Quote Post

Jupiter
*



post 8 Aug, 2009 - 09:55 AM
Post #11
Thanks a lot for this nice tutorial..it works like a charm icon_up.gif
Go to the top of the page
+Quote Post

rkmalbz
*



post 17 Aug, 2009 - 03:08 PM
Post #12
Next, we will build our directory structure. We have our root folder which will hold all our directories, as well as our PHP files. Within this root directory we have a directory named 'images' and another named 'includes'. When we finish we will have a structure that looks like this

CODE

root-directory/images.php
root-directory/index.php
root-directory/upload.php
root-directory/images/
root-directory/includes/conn.php


I'm wondering whats the use of that root-directory..... and how do i put it up?? or how to build the directory?? sorry need some quick basic explanation. anime1.gif

This post has been edited by rkmalbz: 17 Aug, 2009 - 03:13 PM
Go to the top of the page
+Quote Post

neos300
*



post 20 Aug, 2009 - 04:57 AM
Post #13
The root directory is the directory that you will put all your .php files in.
Go to the top of the page
+Quote Post

kewlkreator
Group Icon



post 25 Sep, 2009 - 11:23 AM
Post #14
Thanks so much! It was fun to make!

Root directory:
You really don't have to worry about this. This is the folder where you will put all your files. Since the name of the directory is not needed in this script (other than to view the finished files), this is just another word for "any folder".

This post has been edited by kewlkreator: 25 Sep, 2009 - 11:25 AM
Go to the top of the page
+Quote Post

mulson
*



post 5 Oct, 2009 - 03:56 PM
Post #15
QUOTE(Robsphp @ 10 Jan, 2009 - 04:13 PM) *

akozlik

THANK YOU, I am trying to add to my members database an option to have there own avi file then grab it out of the database and display it.

Would I use the same idea (upload the avi's into a directory then reference them in the users table) ?

regards

Rob


i like the tutorial,but it is possible to display only one image at a time,not neccessary all...this is because i will like to
dispaly only a profile picture for each user,when they login smile.gif

QUOTE(akozlik @ 10 Dec, 2008 - 11:41 AM) *

There have been a lot of posts in the PHP forum regarding how to upload files to a server and put them into a database. A lot of people were trying to put the entire binary file into the database, which was the incorrect way to do things. This tutorial is an attempt to explain how to properly upload images to your website, and store their records in the database using PHP and MySQL.

Please note that this tutorial has a lot of code. The code is well commented and will explain much of what we're trying to do. I'll give an overview in the tutorial, but you need to dig into the code to really understand how things work. Also, please note that this tutorial assumes you know some basics of PHP and MySQL and dont' have any problems writing and reading to and from a database.

The first thing we'll do is build a database. I have created a simple database named 'people', which will hold first and last names of people, as well as a picture of them. You can copy and paste this SQL statement into phpMyAdmin to build your table.

sql

CREATE TABLE `people` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`fname` VARCHAR( 30 ) NOT NULL ,
`lname` VARCHAR( 40 ) NOT NULL ,
`filename` VARCHAR( 50 ) NOT NULL
) ENGINE = MYISAM ;


Next, we will build our directory structure. We have our root folder which will hold all our directories, as well as our PHP files. Within this root directory we have a directory named 'images' and another named 'includes'. When we finish we will have a structure that looks like this

CODE

root-directory/images.php
root-directory/index.php
root-directory/upload.php
root-directory/images/
root-directory/includes/conn.php


Within the includes/conn.php file, you should paste this code:

php

<?php

// Input your information for the database here

// Host name
$host = "localhost";

// Database username
$username = "username";

// Database password
$password = "password";

// Name of database
$database = "db_name";

$conn = mysql_connect($host, $username, $password) or die ("Could not connect");
$db = mysql_select_db($database, $conn) or die ("Could not select DB");

?>


On any page that connects to the database, you will require() this file. Be sure to save that file as conn.php within the includes folder.

Next we build our index file. For us, this will just be a form with three fields. One will be 'fname', one will be 'lname', and the next will be a file upload named 'image'. Please note I did some basic CSS styling, but if you don't want to style it that's fine.

php

<?php
// Start a session for displaying any form errors
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Dream in code tutorial</title>

<style type="text/css">
label
{
float: left;
text-align: right;
margin-right: 10px;
width: 100px;
color: black;
}

#submit
{
float: left;
margin-top: 5px;
position: relative;
left: 110px;
}

#error
{
color: red;
font-weight: bold;
font-size: 16pt;
}
</style>
</head>

<body>

<div>
<?php
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p>
<label>First Name</label>
<input type="text" name="fname" /><br />

<label>Last Name</label>
<input type="text" name="lname" /><br />

<label>Upload Image</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input type="submit" id="submit" value="Upload" />
</p>
</form>
</div>
</body>
</html>


Make sure you notice that we are starting a session at the very top of the page. This will be handy for reporting any errors we have with the form. In addition, we have some code before the form to display any errors that are encountered. After displaying the error message we unset the error session variable.

Another thing to note is the MAX_FILE_SIZE. This can be used to ensure that the filesize of the file uploaded is less than that variable. I've left you on your own to write that portion of the script, but I promise you it is not hard.

Save that file as index.html in your root directory.


Now comes the important part. Here is the entire source file with comments. I will briefly go over how it works, but the details are within the source code:

php

<?php
// Start a session for error reporting
session_start();

// Call our connection file
require("includes/conn.php");

// Check to see if the type of file uploaded is a valid image type
function is_valid_type($file)
{
// This is an array that holds all the valid image MIME types
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif");

if (in_array($file['type'], $valid_types))
return 1;
return 0;
}

// Just a short function that prints out the contents of an array in a manner that's easy to read
// I used this function during debugging but it serves no purpose at run time for this example
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}

// Set some constants

// This variable is the path to the image folder where all the images are going to be stored
// Note that there is a trailing forward slash
$TARGET_PATH = "images/";

// Get our POSTed variables
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$image = $_FILES['image'];

// Sanitize our inputs
$fname = mysql_real_escape_string($fname);
$lname = mysql_real_escape_string($lname);
$image['name'] = mysql_real_escape_string($image['name']);

// Build our target path full string. This is where the file will be moved do
// i.e. images/picture.jpg
$TARGET_PATH .= $image['name'];

// Make sure all the fields from the form have inputs
if ( $fname == "" || $lname == "" || $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: index.php");
exit;
}

// Check to make sure that our file is actually an image
// You check the file type instead of the extension because the extension can easily be faked
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: index.php");
exit;
}

// Here we check to see if a file with that name already exists
// You could get past filename problems by appending a timestamp to the filename and then continuing
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: index.php");
exit;
}

// Lets attempt to move the file from its temporary directory to its new home
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
// NOTE: This is where a lot of people make mistakes.
// We are *not* putting the image into the database; we are putting a reference to the file's location on the server
$sql = "insert into people (fname, lname, filename) values ('$fname', '$lname', '" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
header("Location: images.php");
exit;
}
else
{
// A common cause of file moving failures is because of bad permissions on the directory attempting to be written to
// Make sure you chmod the directory to be writeable
$_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory";
header("Location: index.php");
exit;
}
?>


Alright, so we start out by starting a session and requiring our conn.php file. Nothing new there.

Next, we have a function that checks to see if the upload file is of a valid type. This function helps deter people from uploading exe files, as well as other potentially harmful stuff you don't want on your server. We have a variable that holds all the valid MIME types. That list is by no means exhaustive, but it works for our purposes. For a full list of MIME types check out the Webmaster Tookit's list

The next function is just something I use for debugging. This prints the contents of an array so that it's readable.

We create a constant variable that will hold our target path. I didn't use the define() function, but I could have.

Next block of code checks to make sure none of the fields were blank. This is just very basic form validation and can be adjusted for what you see fit.

The next block makes a call to the is_valid_type function and checks to make sure that the file is valid.

The next block of code checks to see if a file of that name already exists, in an effort to keep people from overwriting files. A good way to ensure a unique filename is to parse out the name part of the file name before the period, append a timestamp, and then hash it. After hashing it, add the extension back on. I'm attempting to keep this tutorial simple, so I did not show that, but you should be able to figure that out. Just use substrings.

Finally, we attempt to move the uploaded file to the new directory. Make sure the new directory has proper write permissions, or your script won't be able to save.

If moving the file was successful, we input the information into the database. Make sure you notice that we do not input the binary file into the database. What we have done is moved the file to a directory where we can access it, and then stored the images file name into the database. Whenever we want to print out the image we get its file name from the database and then build the img tag.


Lastly, we have our images.php page, which will display all those great images you've uploaded.

php

<?php
// Get our database connector
require("includes/conn.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Dream in code tutorial - List of Images</title>
</head>

<body>

<div>

<?php
// Grab the data from our people table
$sql = "select * from people";
$result = mysql_query($sql) or die ("Could not access DB: " . mysql_error());

while ($row = mysql_fetch_assoc($result))
{
echo "<div class=\"picture\">";
echo "<p>";

// Note that we are building our src string using the filename from the database
echo "<img src=\"images/" . $row['filename'] . "\" alt=\"\" /><br />";
echo $row['fname'] . " " . $row['lname'] . "<br />";
echo "</p>";
echo "</div>";
}

?>

</div>
</body>
</html>


There's really nothing there that you shouldn't be able to understand.

Well, that's all I have for you! Now you know how to properly upload images to a website and store their references into the database. You get two thumbs up icon_up.gif icon_up.gif .

If you've found this tutorial useful, or if you have any comments let me know! Good luck!



i like the tutorial,but it is possible to display only one image at a time,not neccessary all...this is because i will like to
dispaly only a profile picture for each user,when they login.
Go to the top of the page
+Quote Post

akozlik
Group Icon



post 6 Oct, 2009 - 10:03 AM
Post #16

Just add a where clause that selects the image associated to the user profile.

You could have a db schema like the following

users
- user_id
- username
- password
- last_login_date

user_profiles
- user_id
- fname
- lname
- profile_image

When you input a user into the users table, you also input a blank record into user profiles where user_id equals the last inserted id on the users table. You can get this with the mysql_insert_id() function.

Then you do a sql like

sql

select profile_image from user_profiles where user_id = '$user_id'


That should be enough to get you started.
Go to the top of the page
+Quote Post

mulson
*



post 8 Oct, 2009 - 11:45 PM
Post #17
QUOTE(akozlik @ 6 Oct, 2009 - 10:03 AM) *

Just add a where clause that selects the image associated to the user profile.

You could have a db schema like the following

users
- user_id
- username
- password
- last_login_date

user_profiles
- user_id
- fname
- lname
- profile_image

When you input a user into the users table, you also input a blank record into user profiles where user_id equals the last inserted id on the users table. You can get this with the mysql_insert_id() function.

Then you do a sql like

sql

select profile_image from user_profiles where user_id = '$user_id'


That should be enough to get you started.


Ok,I will start with that,and will alert you later...thanx alot)
Go to the top of the page
+Quote Post

mulson
*



post 14 Oct, 2009 - 05:20 AM
Post #18
QUOTE(mulson @ 8 Oct, 2009 - 11:45 PM) *

QUOTE(akozlik @ 6 Oct, 2009 - 10:03 AM) *

Just add a where clause that selects the image associated to the user profile.

You could have a db schema like the following

users
- user_id
- username
- password
- last_login_date

user_profiles
- user_id
- fname
- lname
- profile_image

When you input a user into the users table, you also input a blank record into user profiles where user_id equals the last inserted id on the users table. You can get this with the mysql_insert_id() function.


Then you do a sql like

sql

select profile_image from user_profiles where user_id = '$user_id'


That should be enough to get you started.


Ok,I will start with that,and will alert you later...thanx alot)



my table is like this:
employees-table name
name
email
phone
photo
and i run my code like this:
<html>
<head>
<title>photos</title>
</head>
<body>
<table width=800 height=600><tr><td><nop></td><td>
<?php
//lets make connection to the database
include "config.php";

$name= $_POST['name'];
$email= $_POST['email'];
$phone = $_POST['phone'];
$photo = $_POST['photo'];

//request for the message itself
$query = "SELECT photo from employees where name='$name';
";
$thm = mysql_query($query);

if(!$thm) puterror("ERROR:a mistake occured,messages cannot shown");

//Total number of shown messages
//$count = mysql_result($tot,0);

//Puts it into an array
while($info = mysql_fetch_array( $thm))
{
//Outputs the image and other data
echo "<img src=http://senkerr.vndv.com/images/$info[photo] width=100 height=100><br>";
Echo "<b>Name:</b> ".$info['name'] . "<br> ";
Echo "<b>Email:</b> ".$info['email'] . " <br>";
Echo "<b>Phone:</b> ".$info['phone'] . " <hr>";
}
?>
There is no mistake,but there is no image....can you help me out,please?
why is the image not coming,the field that holds the image is photo(it holds only the image name with its extension(.jpeg,.png,.gif...))
Go to the top of the page
+Quote Post

akozlik
Group Icon



post 14 Oct, 2009 - 08:24 AM
Post #19
Check the HTML source code. Is the image creating a full URL to an image? If so, make sure that the image is actually in the directory it's expected to be.

Let me know what you find.
Go to the top of the page
+Quote Post


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/21/09 05:10AM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month