Hi,

Can anyone help me here, I want to display an image using the path of the image and the image title from a mysql db?

I can upload the info to the db, but I have trouble displaying the image.
Here is the code:

CREATE TABLE `trailer` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(64) NOT NULL,
  `model` text NOT NULL,
  `year` text NOT NULL,
  `price` text NOT NULL,
  `location` text NOT NULL,
  `path` text NOT NULL,
  PRIMARY KEY  (`id`)
);
<?php
$db_host = 'localhost'; // don't forget to change 
$db_user = 'root'; 
$db_pwd = 'colum';
$database = 'colum';
$table = 'trailer';// use the same name as SQL table
$password = 'kinefad';// simple upload restriction,// to disallow uploading to everyone
if (!mysql_connect($db_host, $db_user, $db_pwd))    
	die("Can't connect to database");
if (!mysql_select_db($database))    
	die("Can't select database");
// This function makes usage of// $_GET, $_POST, etc... variables
// completly safe in SQL queries
function sql_safe($s){    
	if (get_magic_quotes_gpc())        
		$s = stripslashes($s);    
	return mysql_real_escape_string($s);
}
// If user pressed submit in one of the forms
if ($_SERVER['REQUEST_METHOD'] == 'POST'){    
	// cleaning title field    
	$title = trim(sql_safe($_POST['title']));  
	$model = trim(sql_safe($_POST['model']));
	$year = trim(sql_safe($_POST['year']));
	$price = trim(sql_safe($_POST['price']));
	$location = trim(sql_safe($_POST['location']));
	$path = './images/';
if ($title == '') // if title is not set        
		$title = '(empty title)';// use (empty title) string    
	if ($_POST['password'] != $password)  // cheking passwors        
		$msg = 'Error: wrong upload password';    
	else    
	{        
	if (isset($_FILES['photo']))        
	{                       
		if (!isset($msg)) // If there was no error            
		{                
			// Preparing data to be used in MySQL query                
			mysql_query("INSERT INTO {$table} SET 

title='$title',model='$model',year='$year',price='$price',location='$location',path='$path'");                
			$msg = 'Success: image uploaded';            
		}        
	}        
	elseif (isset($_GET['title']))      // isset(..title) needed            
		$msg = 'Error: file not loaded';
			// to make sure we've using                                            
			// upload form, not form                                            
			// for deletion           
	if (isset($_POST['del'])) // If used selected some photo to delete        
	{                         // in 'uploaded images form';            
		$id = intval($_POST['del']);            
		mysql_query("DELETE FROM {$table} WHERE id=$id");            
		$msg = 'Photo deleted';        
	}    
	}
}
?>
<html><head>
<title>Administration Page</title>
</head>
<body>
<?php
if (isset($msg)) // this is special section for                 
		// outputing message
{
?>
<p style="font-weight: bold;"><?=$msg?>
<br>
<a href="<?=$PHP_SELF?>">reload page</a>
<!-- I've added reloading link, because     
	refreshing POST queries is not good idea -->
</p>
<?php
}
?>
<h1>Administration Page
</h1>
<h2>Uploaded images:</h2>
<form action="<?=$PHP_SELF?>" method="post">
<!-- This form is used for image deletion -->

</form>
<h2>Upload new image:</h2>
<form action="<?=$PHP_SELF?>" method="POST" enctype="multipart/form-data">
<label for="title">Title:</label><br>
<input type="text" name="title" id="title" size="64"><br><br>
<label for="model">Model:</label><br>
<input type="text" name="model" id="model" size="64"><br><br>
<label for="year">Year:</label><br>
<input type="text" name="year" id="year" size="64"><br><br>
<label for="price">Price:</label><br>
<input type="text" name="price" id="price" size="64"><br><br>
<label for="location">Location:</label><br>
<input type="text" name="location" id="location" size="64"><br><br>
<label for="photo">Photo:</label><br>
<input type="file" name="photo" id="photo"><br><br>
<label for="password">Password:</label><br>
<input type="password" name="password" id="password"><br><br>
<input type="submit" value="upload">
</form>
</body>
</html>

Here is my bad attempt of the display page:

<?
$dbcnx = @mysql_connect("localhost", "root", "colum"); 

if (!$dbcnx) 
{
echo( "connection to database server failed!" ); 
exit(); 
} 

if (! @mysql_select_db("colum") ) 
{ 
echo( "Image Database Not Available!" ); 
exit(); 
} 

$result = @mysql_query("SELECT * FROM trailer WHERE id=1"); 

if (!$result) 
{ 
echo("Error performing query: " . mysql_error() . ""); 
exit(); 
} 

while ( $row = mysql_fetch_array($result) ) 
{ 
$title = $row["title"];
$path = $row["path"];
} 

?> 


<html> 

<body> 

<img src="images/$title.JPG"> 

</body> 

</html>

Can anyone help me as to where or what I am doing wrong here?

Thanks

Dani AI

Generated

Short diagnosis and the fix in one sentence: the HTML <img> tag must receive a real, web-accessible filename or URL from PHP (not a literal token), and the file must actually exist in the images folder after upload. Typical mistakes are storing only the upload directory instead of the final filename, building filenames from user-supplied titles, relying on short PHP tags, or using a filesystem path where the web server expects a URL path.

A minimal, safe way to fetch the stored path/alt text and render the image (using mysqli and proper escaping):

<?php
$mysqli = new mysqli('localhost','dbuser','dbpass','dbname');
if ($mysqli->connect_errno) exit('DB error');

$id = isset($_GET['id']) ? (int)$_GET['id'] : 1;
$stmt = $mysqli->prepare('SELECT title, path FROM trailer WHERE id = ? LIMIT 1');
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($title, $path);
if ($stmt->fetch()) {
    $src = htmlspecialchars($path, ENT_QUOTES, 'UTF-8');   // store paths like "images/filename.jpg"
    $alt = htmlspecialchars($title, ENT_QUOTES, 'UTF-8');
    echo '<img src="' . $src . '" alt="' . $alt . '">';
}
$stmt->close();
$mysqli->close();
?>

Quick troubleshooting checks (server-side):

  • Confirm the upload handler actually uses move_uploaded_file() and saves the final filename (for example "images/unique-name.jpg") into the DB.
  • Verify the stored path is a web path (relative to document root) — not a local filesystem path — and that file permissions allow the webserver to read it.
  • Test existence with the filesystem path before output:
    file_exists($_SERVER['DOCUMENT_ROOT'].'/'.ltrim($src,'/')) and show a friendly fallback if missing.
  • Use full PHP tags <?php (short tags can be disabled), escape attributes with htmlspecialchars, and avoid constructing filenames from untrusted fields like title.

pointed to a related discussion; the additions above focus on ensuring the file is actually saved, the DB holds the correct URL/filename, and the PHP echoes that value into src securely.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.