0

Hi, I am a complete newbie when it comes to php. I have been searching google for a way to upload multiple pictures to a directory at one time, and at the SAME time store each pictures path into a table in the database. I have found several examples of upload scripts, but how would i get each pictures path stored in the database? Also, is there a way to have an unlimited amount of upload fields in php, or will it always be a fixed amount just as I have THREE fixed fields below:

<input name="uploaded" type="file" /><br>
<input name="uploaded" type="file" /><br>
<input name="uploaded" type="file" />

I just don't know where to start...

Thanks in advance

7
Contributors
37
Replies
76
Views
7 Years
Discussion Span
Last Post by Gloak
1

Ok here my code try to understand
First create a table named 'img' in your database as fields and data types mentioned below

id int(11) auto_increment
img_base_name varchar(50)
img_ext varchar(50)
img_height int(11)
img_width int(11)
size varchar(50)
Delete img_status enum('Y','N') NO Y

Then provide the 'hostname', 'username', 'password', 'database_name' in line 3 and 4 of my code if applicable.

Then create a folder named 'upload' for storing the uploaded images
And try the following code, good luck

<?php
$con=mysql_connect("localhost", "root", "rootwdp")or die("cannot connect");
mysql_select_db("student",$con)or die("cannot select DB");

if(isset($_POST['upload']))
{	
	$img=$_FILES["image"]["name"];
	foreach($img as $key => $value)
	{
		$name=$_FILES["image"]["name"][$key] ;
		$tname=$_FILES["image"]["tmp_name"][$key];
		$size=$_FILES["image"]["size"][$key];
		$oext=getExtention($name);
		$ext=strtolower($oext);
		$base_name=getBaseName($name);
		if($ext=="jpg" || $ext=="jpeg" || $ext=="bmp" || $ext=="gif"){
			if($size< 1024*1024){
				if(file_exists("upload/".$name)){
					move_uploaded_file($tname,"upload/".$name);
					$result = 1;
					list($width,$height)=getimagesize("upload/".$name);
					$qry="select id from img where `img_base_name`='$base_name' and `img_ext`='$ext'";
					$res=mysql_fetch_array(mysql_query($qry));
					$id=$res['id'];
					$qry="UPDATE img SET `img_base_name`='$base_name' ,`img_ext`='$ext' ,`img_height`='$height' ,`img_width`='$width' ,`size`='$size' ,`img_status`='Y' where id=$id";
					mysql_query($qry);
					echo "Image '$name' updated<br />";
				}
				else{
					move_uploaded_file($tname,"upload/".$name);
					$result = 1;
					list($width,$height)=getimagesize("upload/".$name);
					$qry="INSERT INTO `img`(`id` ,`img_base_name` ,`img_ext` ,`img_height` ,`img_width`, `size` ,`img_status`)VALUES (NULL , '$base_name', '$ext', '$height', '$width', '$size', 'Y');";
					mysql_query($qry);
					echo "Image '$name' uploaded<br />";
				}
			}
			else{
				echo "Image size excedded.<br />File size should be less than 1Mb<br />";
			}
		}
		else{
			echo "Invalid file extention '.$oext'<br />";
		}
	}	
}

function getExtention($image_name){
	return substr($image_name,strrpos($image_name,'.')+1);
}
function getBaseName($image_name){
	return substr($image_name,0,strrpos($image_name,'.'));
}
?>

<!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>Untitled Document</title>
<script type="text/javascript">
function addItems()
{
var table1 = document.getElementById('tab1');
var newrow = document.createElement("tr");
var newcol = document.createElement("td");
var input = document.createElement("input");
input.type="file";
input.name="image[]";
newcol.appendChild(input);
newrow.appendChild(newcol);
table1.appendChild(newrow);
}
function remItems()
{
var table1 = document.getElementById('tab1');
var lastRow = table1.rows.length;
if(lastRow>=2)
table1.deleteRow(lastRow-1);
}
</script>

<style type="text/css">

<a class="tooltip" and them url href="/http.www.anyurl.com" </a>

a.tooltip:hover span{display:inline; position:absolute; border:2px solid #cccccc; background:#efefef; color:#333399;}
a.tooltip span
{display:none; padding:2px 3px; margin-left:8px; width:150px;}

</style>

</head>

<body>

<form method="post" action="" enctype="multipart/form-data">
<table align="center" border="0" id="tab1">
	<tr>
    	<td width="218" align="center"><input type="file" name="image[]" /></td>
		<td width="54" align="center"><img src="Button-Add-icon.png" alt="Add" style="cursor:pointer" onclick="addItems()" /></td>
        <td><img src="Button-Delete-icon.png" alt="Remove" style="cursor:pointer" onclick="remItems()" /></td>
	</tr>
</table>

<table align="center" border="0" id="tab2">
<tr><td align="center"><input type="submit" value="Upload" name="upload" /></td></tr>
</table>
</form>
<table border="0" style="border:solid 1px #333; width:800px" align="center"><tr><td align="center">

<iframe style="display:none" name="if1" id="if1"></iframe>

<?
$qry="select * from img where img_status='Y' order by id";
$res=mysql_query($qry);
$i=0;
if(mysql_num_rows($res)){ ?>
<div align="center"><ul style="width:650px; border: 0px">
<?
while($fetch=mysql_fetch_array($res)){
	$hratio=120/$fetch['img_height'];
	$wratio=120/$fetch['img_width'];
	$ratio=($hratio < $wratio) ? $hratio : $wratio;
	$hth=$fetch['img_height']*$ratio;
	$wth=$fetch['img_width']*$ratio;
?>
<li style="width:120px; height:180px; border:0px solid #333;float:left;list-style:none outside none; padding-right:5px;"><img src="upload/<? echo $fetch['img_base_name'].'.'.$fetch['img_ext']; ?>" width="<? echo $wth; ?>" height="<? echo $hth; ?>" title="<? echo "image : ".$fetch['img_base_name'].".".$fetch['img_ext']; ?>" /><br />
<?
	if($i==0)
		$fp=fopen("fileInfo.txt",'w');
	else
		$fp=fopen("fileInfo.txt",'a');
	fwrite($fp,"Image : ".++$i ."\r\n");
	fwrite($fp,"Name : ".$fetch['img_base_name'].".".$fetch['img_ext']."\r\n");
	fwrite($fp,"width X height :
 ".$fetch['img_width']." X ".$fetch['img_height']."\r\n");
	fwrite($fp,"Size : ".round($fetch['size']/1024,1)."Kb\r\n");
	fwrite($fp,"____________________________________\r\n");
	fclose($fp);

echo $fetch['img_base_name'].".".$fetch['img_ext'].'<br />';
echo $fetch['img_width'].' X ';
echo $fetch['img_height'].'<br />';
echo round($fetch['size']/1024,1) .'Kb';
?>
</li>
<?
}?>
</ul>
</div><? }?>

</td></tr></table>
</body>
</html>

Edited by mahavir123: n/a

0

You are very kind to try and help me with this! I have just started to read over your code, and the first thing I am confused about is in your create table:

Delete img_status enum('Y','N') NO Y

What does that line do? And i'm unsure how to put it in my create table command. Would my "create table" look EXACTLY like this:

create table img (id int NOT NULL auto_increment, img_base_name varchar(50) NOT NULL, img_ext varchar(50) NOT NULL, img_height int(11) NOT NULL, img_width int(11) NOT NULL, size varchar(50) img_status enum('Y','N'), PRIMARY KEY (id));

I have created the table like I showed you above, and files get uploaded to the upload folder correctly, but no information is passed to the img table??

Thanks so much for your help!

0

Well, all is working now! There was just an error in my table because I noticed that you forgot to mention a size field. But all is well! I will be modifying this code to fit my project found here: http://www.daniweb.com/forums/thread315489.html

There were quite a few posts in that thread, and I think it made things more confusing than anything. If you have any suggestions feel free to post! Thanks so much for your script! Would you like me to credit you in my source? If so, please let me know!

0

Also, I forgot to ask what the purpose of the "enum('Y','N')" field is ???? Why is that field necessary?

Thanks!

0

You are contributing the following post:
This looks great! Thanks so much Mahavir - it's generous to provide such detailed code :-) I've only been learning Php for a couple of weeks and your script seemed to make logical sense to me.

... but I have the same problem as dschuett had - I can't get Mysql to update :-(
Dschuett mentioned a problem with a missing 'size' field in Mysql, but this is included in mine. Here's my code - any reason why this shouldn't work? I don't get any error on screen.

Apologies if the answer is obvious, but I'm still developing my debugging capabilities.

Mysql:
id, int(11), auto_increment
img_base_name, varchar(50)
img_ext, varchar(50)
img_height, int(11)
img_width, int(11)
size, varchar(50)
image_status, enum('Y','N')

$con=mysql_connect("localhost", "root", "root")or die("cannot connect");
mysql_select_db("skole",$con)or die("cannot select DB");

if(isset($_POST['upload']))
{	
	$img=$_FILES["image"]["name"];
	foreach($img as $key => $value)
	{
		$name=$_FILES["image"]["name"][$key] ;
		$tname=$_FILES["image"]["tmp_name"][$key];
		$size=$_FILES["image"]["size"][$key];
		$oext=getExtention($name);
		$ext=strtolower($oext);
		$base_name=getBaseName($name);
		if($ext=="jpg" || $ext=="jpeg" || $ext=="bmp" || $ext=="gif"){
			if($size< 1024*1024){
				if(file_exists("upload/".$name)){
					move_uploaded_file($tname,"upload/".$name);
					$result = 1;
					list($width,$height)=getimagesize("upload/".$name);
					$qry="select id from img where `img_base_name`='$base_name' and `img_ext`='$ext'";
					$res=mysql_fetch_array(mysql_query($qry));
					$id=$res['id'];
					$qry="UPDATE img SET `img_base_name`='$base_name' ,`img_ext`='$ext' ,`img_height`='$height' ,`img_width`='$width' ,`size`='$size' ,`img_status`='Y' where id=$id";
					mysql_query($qry);
					echo "Image '$name' updated<br />";
				}
				else{
					move_uploaded_file($tname,"upload/".$name);
					$result = 1;
					list($width,$height)=getimagesize("upload/".$name);
					$qry="INSERT INTO `img`(`id` ,`img_base_name` ,`img_ext` ,`img_height` ,`img_width`, `size` ,`img_status`)VALUES (NULL , '$base_name', '$ext', '$height', '$width', '$size', 'Y');";
					mysql_query($qry);
					echo "Image '$name' uploaded<br />";
				}
			}
			else{
				echo "Image size excedded.<br />File size should be less than 1Mb<br />";
			}
		}
		else{
			echo "Invalid file extention '.$oext'<br />";
		}
	}	
}

function getExtention($image_name){
	return substr($image_name,strrpos($image_name,'.')+1);
}
function getBaseName($image_name){
	return substr($image_name,0,strrpos($image_name,'.'));
}
<!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>Untitled Document</title>
<script type="text/javascript">
function addItems()
{
var table1 = document.getElementById('tab1');
var newrow = document.createElement("tr");
var newcol = document.createElement("td");
var input = document.createElement("input");
input.type="file";
input.name="image[]";
newcol.appendChild(input);
newrow.appendChild(newcol);
table1.appendChild(newrow);
}
function remItems()
{
var table1 = document.getElementById('tab1');
var lastRow = table1.rows.length;
if(lastRow>=2)
table1.deleteRow(lastRow-1);
}
</script>

<style type="text/css">

<a class="tooltip" and them url href="/http.www.anyurl.com" </a>

a.tooltip:hover span{display:inline; position:absolute; border:2px solid #cccccc; background:#efefef; color:#333399;}
a.tooltip span
{display:none; padding:2px 3px; margin-left:8px; width:150px;}

</style>

</head>

<body>

<form method="post" action="" enctype="multipart/form-data">
<table align="center" border="0" id="tab1">
	<tr>
    	<td width="218" align="center"><input type="file" name="image[]" /></td>
		<td width="54" align="center"><img src="Button-Add-icon.png" alt="Add" style="cursor:pointer" onclick="addItems()" /></td>
        <td><img src="Button-Delete-icon.png" alt="Remove" style="cursor:pointer" onclick="remItems()" /></td>
	</tr>
</table>

<table align="center" border="0" id="tab2">
<tr><td align="center"><input type="submit" value="Upload" name="upload" /></td></tr>
</table>
</form>
<table border="0" style="border:solid 1px #333; width:800px" align="center"><tr><td align="center">

<iframe style="display:none" name="if1" id="if1"></iframe>

<?
$qry="select * from img where img_status='Y' order by id";
$res=mysql_query($qry);
$i=0;
if(mysql_num_rows($res)){ ?>
<div align="center"><ul style="width:650px; border: 0px">
<?
while($fetch=mysql_fetch_array($res)){
	$hratio=120/$fetch['img_height'];
	$wratio=120/$fetch['img_width'];
	$ratio=($hratio < $wratio) ? $hratio : $wratio;
	$hth=$fetch['img_height']*$ratio;
	$wth=$fetch['img_width']*$ratio;
?>
<li style="width:120px; height:180px; border:0px solid #333;float:left;list-style:none outside none; padding-right:5px;"><img src="upload/<? echo $fetch['img_base_name'].'.'.$fetch['img_ext']; ?>" width="<? echo $wth; ?>" height="<? echo $hth; ?>" title="<? echo "image : ".$fetch['img_base_name'].".".$fetch['img_ext']; ?>" /><br />
<?
	if($i==0)
		$fp=fopen("fileInfo.txt",'w');
	else
		$fp=fopen("fileInfo.txt",'a');
	fwrite($fp,"Image : ".++$i ."\r\n");
	fwrite($fp,"Name : ".$fetch['img_base_name'].".".$fetch['img_ext']."\r\n");
	fwrite($fp,"width X height :
 ".$fetch['img_width']." X ".$fetch['img_height']."\r\n");
	fwrite($fp,"Size : ".round($fetch['size']/1024,1)."Kb\r\n");
	fwrite($fp,"____________________________________\r\n");
	fclose($fp);

echo $fetch['img_base_name'].".".$fetch['img_ext'].'<br />';
echo $fetch['img_width'].' X ';
echo $fetch['img_height'].'<br />';
echo round($fetch['size']/1024,1) .'Kb';
?>
</li>
<?
}?>
</ul>
</div><? }?>

</td></tr></table>
</body>
</html>
0

Change line 21 to this:
$qry="select id from img where img_base_name='$base_name' and img_ext='$ext'";

Change line 24 to this:
$qry="UPDATE img SET img_base_name='$base_name', img_ext='$ext', img_height='$height', img_width='$width', size='$size', img_status='Y' where id=$id";

and line 32 to this:
$qry="INSERT INTO img(id, img_base_name, img_ext, img_height, img_width, size, img_status)VALUES (NULL , '$base_name', '$ext', '$height', '$width', '$size', 'Y');"

*Note there was also an extra ; at the end of the above line that I removed.

If you are still having problems do a print_r($qry); right after line 33. This will show you your query.

Let me know if you are still having problems!

0

enum('Y','N')
It is like a enumeration data type to a field in MySQL database which will only take values 'Y' (Uppercase Y) and 'N' (Uppercase N) in the table.
Try to enter other characters in your enum field into the database you will understand.

You can set different data types also like:
Ex:
enum('1','2','3','4')
enum('y','n')
enum('on','off')

All values will be enclosed in single quote and separated by comma.

0

Thanks so much for reading through the code and making amendments - it's really appreciated!

I made the changes but still no luck :-( I've been playing with the code all day, but to be honest my Php skills aren't strong enough to see the problems. I'm building this site back-end in order to learn about Php, but I'm only a couple of weeks in...

I tried the print_r and get values when a new, not-previously-uploaded image is uploaded:

INSERT INTO img (id, img_base_name, img_ext, img_height, img_width, size, img_status)VALUES (NULL , 'Ågotnes Hotell4', 'jpg', '567', '850', '427427', 'Y')

I have full permissions on the table. I changed the image_status default to Y and made id a primary (not sure if that makes any difference). The table is currently empty, but I've tried adding values to no avail. When values are added, images are not being echoed either - Firefox just shows:

" />
'; echo $fetch.' X '; echo $fetch.'
'; echo round($fetch/1024,1) .'Kb'; ?>

I'm normally too stubborn to ask for help, especially when I know I'm probably doing something dumb or there's just some typo, but... please help if you have time!

0

Thanks so much for reading through the code and making amendments - it's really appreciated!

I made the changes but still no luck :-( I've been playing with the code all day, but to be honest my Php skills aren't strong enough to see the problems. I'm building this site back-end in order to learn about Php, but I'm only a couple of weeks in...

I tried the print_r and get values when a new, not-previously-uploaded image is uploaded:

INSERT INTO img (id, img_base_name, img_ext, img_height, img_width, size, img_status)VALUES (NULL , 'Ågotnes Hotell4', 'jpg', '567', '850', '427427', 'Y')

I have full permissions on the table. I changed the image_status default to Y and made id a primary (not sure if that makes any difference). The table is currently empty, but I've tried adding values to no avail. When values are added, images are not being echoed either - Firefox just shows:

" />
'; echo $fetch.' X '; echo $fetch.'
'; echo round($fetch/1024,1) .'Kb'; ?>

I'm normally too stubborn to ask for help, especially when I know I'm probably doing something dumb or there's just some typo, but... please help if you have time!

please re-post your new code, and i will gladly look through it for you!

0

Hi dschuett

I'm not entirely sure what the problem was with updating the mysql table, but I deleted and recreated the table (in order to send you the SQL create code) and the update now seems to work fine! I must have just screwed up one of the fields :-S

In regards to echoing the values, I changed some of the <? tags to <?php and this seemed to fix this. So I think the form is now performing exactly as it should! I need to allow file names to include å, ø and æ (since I'm living in Norway), but I'm guessing I can figure that out easily enough.

I also want to explore ways for the user to click a 'delete' button next to each image to remove image from directory / mysql, so they don't need the original file in order to delete a file. If I manage to find a solution to this I'll post this here as I think it would be quite a useful function to integrate.

I'm guessing somehow to dynamically create a (form) delete button, giving the button id the same name as the image $id, and sending it as a _GET (to action="delete.php") which will DELETE row / Delete file and return to a refreshed page. Do you think that sounds like a reasonable / logical method or am I missing something stupidly obvious?

Many thanks again to you (and Mahavir) for giving me a way forward :)

0

Hi dschuett

I'm not entirely sure what the problem was with updating the mysql table, but I deleted and recreated the table (in order to send you the SQL create code) and the update now seems to work fine! I must have just screwed up one of the fields :-S

In regards to echoing the values, I changed some of the <? tags to <?php and this seemed to fix this. So I think the form is now performing exactly as it should! I need to allow file names to include å, ø and æ (since I'm living in Norway), but I'm guessing I can figure that out easily enough.

I also want to explore ways for the user to click a 'delete' button next to each image to remove image from directory / mysql, so they don't need the original file in order to delete a file. If I manage to find a solution to this I'll post this here as I think it would be quite a useful function to integrate.

I'm guessing somehow to dynamically create a (form) delete button, giving the button id the same name as the image $id, and sending it as a _GET (to action="delete.php") which will DELETE row / Delete file and return to a refreshed page. Do you think that sounds like a reasonable / logical method or am I missing something stupidly obvious?

Many thanks again to you (and Mahavir) for giving me a way forward :)

Good to hear you got things working! <? is referred to as a short open tag. You can enable this option in your php.ini file, but I always recommend using the full <?php open tag.

As far as providing a delete link you can most definitely do this in such a way that you have explained. Simply pass the $id through your link with the following:

echo "<a href=\"delete.php?id=".$row['id']."\">Delete Picture</a>";

Then in your delete script just call the id by setting a variable as:

$id = $_GET['id'];

Let me know how it works out!

0

So, I just notice that in IE(8), the add and remove buttons don't work. Well...the add button works, the remove button does NOT. Any ideas why this may be?

0

Please can you look at my 'altered' code? It uploads the pictures fine, but doesn't upload the information to the database.

My db table is like yours, but it is called 'testimonials', my userid is Testimonial_Id, and i have extra fields, CustomerName, Town, Testimonial and SortOrder.
Thanks in advance,
Steve

<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}

// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
  $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
  //to fully log out a visitor we need to clear the session varialbles
  $_SESSION['MM_Username'] = NULL;
  $_SESSION['MM_UserGroup'] = NULL;
  $_SESSION['PrevUrl'] = NULL;
  unset($_SESSION['MM_Username']);
  unset($_SESSION['MM_UserGroup']);
  unset($_SESSION['PrevUrl']);
	
  $logoutGoTo = "index.php";
  if ($logoutGoTo) {
    header("Location: $logoutGoTo");
    exit;
  }
}
?>
<?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && true) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}

$MM_restrictGoTo = "index.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0) 
  $MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}

$con=mysql_connect("localhost", "xxxxxxxxxxx", "xxxxxxxxxxx")or die("cannot connect");
mysql_select_db("xxxxxxxxxxxxxxxx",$con)or die("cannot select DB");
if(isset($_POST['upload']))
{	
	$img=$_FILES["image"]["name"];
	foreach($img as $key => $value)
	{
		$name=$_FILES["image"]["name"][$key] ;
		$tname=$_FILES["image"]["tmp_name"][$key];
		$size=$_FILES["image"]["size"][$key];
		$oext=getExtention($name);
		$ext=strtolower($oext);
		$base_name=getBaseName($name);
		if($ext=="jpg" || $ext=="jpeg" || $ext=="bmp" || $ext=="gif"){
			if($size< 1024*1024){
				if(file_exists("uploaded_images/".$name)){
					move_uploaded_file($tname,"uploaded_images/".$name);
					$result = 1;
					list($width,$height)=getimagesize("uploaded_images/".$name);
					$qry="select Testimonial_Id from testimonials where `img_base_name`='$base_name' and `img_ext`='$ext'";
					$res=mysql_fetch_array(mysql_query($qry));
					$id=$res['Testimonial_Id'];
					$qry="UPDATE testimonials SET `img_base_name`='$base_name' ,`img_ext`='$ext' ,`img_height`='$height' ,`img_width`='$width' ,`size`='$size' ,`img_status`='Y' where Testimonial_Id=$id";
					
					mysql_query($qry);
					echo "Image '$name' updated<br />";
				}
				else{
					move_uploaded_file($tname,"uploaded_images/".$name);
					$result = 1;
					list($width,$height)=getimagesize("uploaded_images/".$name);
				  mysql_real_escape_string($_POST['customername']);
                  mysql_real_escape_string($_POST['town']);
                  mysql_real_escape_string($_POST['testimonial']);
                  mysql_real_escape_string($_POST['sort_order']);
				  
					$qry="INSERT INTO testimonials(`Testimonial_Id` ,'CustomerName' ,'Town' ,'Testimonial' ,'SortOrder' ,`img_base_name` ,`img_ext` ,`img_height` ,`img_width`, `size` ,`img_status`)VALUES ('' , 'customername' , 'town' , 'testimonial' , 'sort_order' , '$base_name', '$ext', '$height', '$width', '$size', 'Y');";
				  
					mysql_query($qry);
					echo "Image '$name' uploaded<br />";
				}
			}
			else{
				echo "Image size excedded.<br />File size should be less than 1Mb<br />";
			}
		}
		else{
			echo "Invalid file extention '.$oext'<br />";
		}
	}	
}

function getExtention($image_name){
	return substr($image_name,strrpos($image_name,'.')+1);
}
function getBaseName($image_name){
	return substr($image_name,0,strrpos($image_name,'.'));
}
?>

<!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>xxxxxxxxxxxxxxxAdmin Area - Add Testimonial</title>
<link href="testimonials.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function addItems()
{
var table1 = document.getElementById('tab1');
var newrow = document.createElement("tr");
var newcol = document.createElement("td");
var input = document.createElement("input");
input.type="file";
input.name="image[]";
newcol.appendChild(input);
newrow.appendChild(newcol);
table1.appendChild(newrow);
}
function remItems()
{
var table1 = document.getElementById('tab1');
var lastRow = table1.rows.length;
if(lastRow>=2)
table1.deleteRow(lastRow-1);
}
</script>

<style type="text/css">

<a class="tooltip" and them url href="/http.www.xxxxxxxxxxxxxxxxx.co.uk" </a>

a.tooltip:hover span{display:inline; position:absolute; border:2px solid #cccccc; background:#efefef; color:#333399;}
a.tooltip span
{display:none; padding:2px 3px; margin-left:8px; width:150px;}

</style>

</head>

<body>
<div align="center">
  <h1><strong>xxxxxxxxxxxxxxxx Administration Area</strong></h1>
</div>
<p align="center">&nbsp;</p>
<form method="post" action="" enctype="multipart/form-data">
  <p>&nbsp;</p>
  <p align="center">
    <label for="customername">Customer Name:</label>
    <input name="customername" type="text" id="customername" maxlength="150" value="<?php echo $_POST['customername']; ?>" />
  </p>
  <p align="center">
    <label for="town">Town/City:   </label>
    <input name="town" type="text" id="town" maxlength="150" value="<?php echo $_POST['town']; ?>" />
  </p>
  <p align="center">
    <label for="testimonial"><u>Testimonial </u></label>
  </p>
  <p align="center">
    <textarea name="testimonial" id="testimonial" cols="60" rows="10"><?php echo $_POST['testimonial']; ?></textarea>
  </p>
  <p align="center">
    <label for="sort_order">Sort Order: </label>
    <input name="sort_order" type="text" id="sort_order" size="10" maxlength="3" value="<?php echo $_POST['sort_order']; ?>" />
  </p>
<table align="center" border="0" id="tab1">
	<tr>
    	<td width="218" align="center"><input type="file" name="image[]" /></td>
		<td width="54" align="center"><img src="images/add_icon.jpg" alt="Add" style="cursor:pointer" onclick="addItems()" /></td>
        <td><img src="images/remove_icon.jpg" alt="Remove" style="cursor:pointer" onclick="remItems()" /></td>
	</tr>
</table>

<table align="center" border="0" id="tab2">
<tr><td align="center"><input type="submit" value="Upload" name="upload" /></td></tr>
</table>
</form>
<table border="0" style="border:solid 1px #333; width:800px" align="center"><tr><td align="center">

<iframe style="display:none" name="if1" id="if1"></iframe>

<?
$qry="select * from testimonials where img_status='Y' order by Testimonial_Id";
$res=mysql_query($qry);
$i=0;
if(mysql_num_rows($res)){ ?>
<div align="center"><ul style="width:650px; border: 0px">
<?
while($fetch=mysql_fetch_array($res)){
	$hratio=120/$fetch['img_height'];
	$wratio=120/$fetch['img_width'];
	$ratio=($hratio < $wratio) ? $hratio : $wratio;
	$hth=$fetch['img_height']*$ratio;
	$wth=$fetch['img_width']*$ratio;
?>
<li style="width:120px; height:180px; border:0px solid #333;float:left;list-style:none outside none; padding-right:5px;"><img src="uploaded_images/<? echo $fetch['img_base_name'].'.'.$fetch['img_ext']; ?>" width="<? echo $wth; ?>" height="<? echo $hth; ?>" title="<? echo "image : ".$fetch['img_base_name'].".".$fetch['img_ext']; ?>" /><br />
<?
	if($i==0)
		$fp=fopen("fileInfo.txt",'w');
	else
		$fp=fopen("fileInfo.txt",'a');
	fwrite($fp,"Image : ".++$i ."\r\n");
	fwrite($fp,"Name : ".$fetch['img_base_name'].".".$fetch['img_ext']."\r\n");
	fwrite($fp,"width X height :
 ".$fetch['img_width']." X ".$fetch['img_height']."\r\n");
	fwrite($fp,"Size : ".round($fetch['size']/1024,1)."Kb\r\n");
	fwrite($fp,"____________________________________\r\n");
	fclose($fp);

echo $fetch['img_base_name'].".".$fetch['img_ext'].'<br />';
echo $fetch['img_width'].' X ';
echo $fetch['img_height'].'<br />';
echo round($fetch['size']/1024,1) .'Kb';
?>
</li>
<?
}?>
</ul>
</div><? }?>

</td></tr></table>
</body>
</html>

Edited by Stevis2002: n/a

0

On line 110:

$qry="INSERT INTO testimonials(`Testimonial_Id` ,'CustomerName' ,'Town' ,'Testimonial' ,'SortOrder' ,`img_base_name` ,`img_ext` ,`img_height` ,`img_width`, `size` ,`img_status`)VALUES ('' , 'customername' , 'town' , 'testimonial' , 'sort_order' , '$base_name', '$ext', '$height', '$width', '$size', 'Y');";

notice you have and extra ';' and it also needs to be before you ending quote.

also some of your single quotes are different... try this:

$qry="INSERT INTO testimonials('Testimonial_Id', 'CustomerName', 'Town', 'Testimonial', 'SortOrder', 'img_base_name', 'img_ext', 'img_height', 'img_width', 'size', 'img_status') VALUES ('', 'customername', 'town', 'testimonial', 'sort_order', '$base_name', '$ext', '$height', '$width', '$size', 'Y')";

if that doesn't work, try doing a var_dump($qry); right after line 110 to see if it is actually filling out your query correctly.

Edited by dschuett: n/a

0

Still nothing going into db mate
dump read...
string(281) "INSERT INTO testimonials('Testimonial_Id', 'CustomerName', 'Town', 'Testimonial', 'SortOrder', 'img_base_name', 'img_ext', 'img_height', 'img_width', 'size', 'img_status') VALUES ('', 'customername', 'town', 'testimonial', 'sort_order', 'untitled3', 'bmp', '50', '50', '7654', 'Y')" Image 'untitled3.bmp' uploaded

0

The images are each using a testimonial_id as well...is it possible to upload them all into the same id?

0

Something has to be wrong with the table then. Try manually using this code to see if it inserts those values...

INSERT INTO testimonials('Testimonial_Id', 'CustomerName', 'Town', 'Testimonial', 'SortOrder', 'img_base_name', 'img_ext', 'img_height', 'img_width', 'size', 'img_status') VALUES ('', 'customername', 'town', 'testimonial', 'sort_order', 'untitled3', 'bmp', '50', '50', '7654', 'Y');
0

Getting syntax error on this line, but i cannot see why...

&qry="INSERT INTO testimonials('Testimonial_Id', 'CustomerName', 'Town', 'Testimonial', 'SortOrder', 'img_base_name', 'img_ext', 'img_height', 'img_width', 'size', 'img_status') VALUES ('', 'customername', 'town', 'testimonial', 'sort_order', 'untitled3', 'bmp', '50', '50', '7654', 'Y')";
0

did you try running this manually:

INSERT INTO testimonials('Testimonial_Id', 'CustomerName', 'Town', 'Testimonial', 'SortOrder', 'img_base_name', 'img_ext', 'img_height', 'img_width', 'size', 'img_status') VALUES ('', 'customername', 'town', 'testimonial', 'sort_order', 'untitled3', 'bmp', '50', '50', '7654', 'Y');
0

Yeah, it gave me the following...

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Testimonial_Id', 'CustomerName', 'Town', 'Testimonial', 'SortOrder', 'img_base_' at line 1
0
CREATE TABLE `testimonials` (
 `Testimonial_Id` int(11) NOT NULL AUTO_INCREMENT,
 `CustomerName` varchar(150) NOT NULL,
 `Town` varchar(150) NOT NULL,
 `Testimonial` varchar(600) NOT NULL,
 `SortOrder` tinyint(5) NOT NULL,
 `Images` varchar(255) DEFAULT NULL,
 `img_base_name` varchar(50) NOT NULL,
 `img_ext` varchar(50) NOT NULL,
 `img_height` int(11) NOT NULL,
 `img_width` int(11) NOT NULL,
 `size` varchar(50) NOT NULL,
 `img_status` enum('Y','N','y','n') NOT NULL,
 PRIMARY KEY (`Testimonial_Id`)
) ENGINE=MyISAM AUTO_INCREMENT=31 DEFAULT CHARSET=latin1
1

Wow, now I feel dumb. I got home from work and was able to look at it for more than a couple seconds at a time. Simple mistake; there shouldn't be any quotes on field names. Your query on line 110 should look like this:

$qry = "INSERT INTO testimonials(Testimonial_Id, CustomerName, Town, Testimonial, SortOrder, img_base_name, img_ext, img_height, img_width, size, img_status) VALUES ('', 'customername', 'town', 'testimonial', 'sort_order', '$base_name', '$ext', '$height', '$width', '$size', 'Y')";

You should be good after you change it to that. Let me know if that works!

Votes + Comments
Amazingly helpful
0

Try running the insert statement manually again to see if it will insert that way. It should insert without any problems; I just used your create table code to make a that same table on my server, and the insert code works fine.

0

Also, make sure the image you are uploading isn't already in your "uploaded_images" directory because if it already exists in there your script is going to try to run you UPDATE query since it already exists. However, it can't UPDATE something that isn't in the database.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.