Display Image from MySQL

I have a table in mysql that has the path’s of images stored. The image path is stored under the column “photo”. The table looks like this:

 1	id
 2	name 
 3	age	
 4	category	
 5	photo	
 6	rating

I want to create a page such as view.php?id=1 where the image is displayed according to the id. It would have to call upon the path to display it. How would I do this?

First of all, get the ID:

[php]if(isset($_GET[‘id’])) {
$id = $_GET[‘id’];
} else {
$id = 0;
}[/php]

Then, check the ID value is numeric. We’ll be using the preg_replace function with a regular expression.

[php]if(preg_match(’/^[0-9]+$/’, $id) == 0) {
// Pattern did not match - ID is invalid
die(‘Invalid ID’);
}[/php]

Then, we’d connect to MySQL and select a database:

[php]$link = mysql_connect(‘hostname’, ‘username’, ‘password’);
mysql_select_db(‘database_name’, $link);[/php]

Followed by running a query to select an item in the database with the ID the user gave:

[php]$query = mysql_query(“SELECT * FROM table_name WHERE table_name.id = '” . $id . “’”);[/php]

Then check if the query ran OK.

[php]if($query == false) {
die(‘MySQL Query Failed!’);
}[/php]

If it wasn’t false, check if it found a matching record:

[php]if(mysql_num_rows($query) == 1) {
// Found!
} else {
echo ‘No image with found with that ID!’;
}[/php]

Once we’ve got a match, get the data and display the image:

[php]if(mysql_num_rows($query) == 1) {
// Found!
$result = mysql_fetch_array($query);

echo '<img src="', $result['photo'], '">';

} else {
echo ‘No image with found with that ID!’;
}[/php]

For explanations of the functions used:

preg_match
mysql_connect
mysql_select_db
mysql_num_rows
mysql_fetch_array

If you’ve never heard of or used regular expressions before, they’re a great tool and a really useful thing to have learned how to use. You could look at a quck start tutorial and test your regular expressions with a tool such as Rubular.

Let me know if this doesn’t work or you want any parts explaining or any help implementing this in your page :slight_smile:

Sponsor our Newsletter | Privacy Policy | Terms of Service