Hello.

I'm getting an undefined index error with the following code and I can't for the life of me figure out why. Any insight would be greatly appreciated.

I'm using an html form and a PHP file to upload images to a directory and write the rest of the form details to my DB. The images get uploaded to the directory just fine, but it's not writing the rest of the data to the DB for some reason.

.html form

<html>
<form enctype="multipart/form-data" action="add.php" method="POST"> 
Name: <input type="text" name="name"><br> 
E-mail: <input type="text" name = "email"><br> 
Phone: <input type="text" name = "phone"><br> 
Photo: <input type="file" name="photo"><br> 
<input type="submit" value="Add"> 
</form>
</html>

and here is the add.php file for uploading and writing to the database

<?php 
//This is the directory where images will be saved 
$target = 'images/'; 
$target = $target . basename( $_FILES['photo']['name']); 

//This gets all the other information from the form 
$name=$_POST['name']; 
$email=$_POST['email']; 
$phone=$_POST['phone']; 
$pic=($_FILES['photo']['name']); 

// Connects to your Database 
mysql_connect("localhost", "un", "pw") or die(mysql_error()) ; 
mysql_select_db("database") or die(mysql_error()) ; 

//Writes the information to the database 
mysql_query("INSERT INTO `products` VALUES ('$name', '$email', '$phone', '$pic')") ; 

//Writes the photo to the server 
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) 
{ 

//Tells you if its all ok 
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; 
} 
else { 

//Gives and error if its not 
echo "Sorry, there was a problem uploading your file."; 
} 
?>

the undefined index error I'm getting is:
"Undefined index: uploadedfile in /Applications/MAMP/htdocs/upload/add.php on line 24"

then below that I get the upload confirmation message that reads;
"The file has been uploaded, and your information has been added to the directory"


thanks a lot in advance!

$_FILES

Shouldn't this be $_FILES :)

commented: Fantastic!!!! +1

DOH!
Thank you!! Thank you! It works now!

:) Great !

Hey man!

i got a question maybe you can help me with this....

the HTML CODE: (inserir_produto.php)

<style>

span {width: 150;}

</style>

  <form action='inserir_produto1.php' method="post">
	<h3><b>Inserir Produto</b></h3>
    <span>Marca: </span><input type='text' name='marca' />
    <br />
    <span>Cor Principal: </span><input type='text' name='cor' />
    <br />
    <span>Material de Fabrico: </span><input type='text' name='matfabrico' />
    <br />
    <span>Altura: </span><input type='text' name='altura' />
    <br />
    <span>Largura: </span><input type='text' name='largura' />
    <br />
    <span>Referência: </span><input type='text' name='ref' />
    <br />
    <span>Foto: </span><input type="file" name="file" />
    <br />
    <span>Descrição: </span><input type='text' name='descricao' />
    <br />
    <input type='submit' name='submit1' value='Adicionar Produto' id='submit1' />
    <input type="reset" value="Limpar Tudo" />
    <br />
	</form>

AND THIS IS THE PHP CODE: (inserir_produto.php)

<?php 



if (isset($_POST['submit1']))
	if(	$_POST['marca']!=''			&&
		$_POST['cor']!=''			&&
		$_POST['matfabrico']!=''	&&
		$_POST['altura']!=''		&&
		$_POST['largura']!=''		&&
		$_POST['ref']!=''			&&
		$_POST['file']!=''			&&
		$_POST['descricao']!='')
		
		{
	mysql_connect('localhost','root','');

	mysql_select_db('albino');
	
	
	$sql2="SELECT * from produtos WHERE referencia ='" . $_POST['ref'] . "'";
	$resultado=mysql_query($sql2);
				mysql_fetch_array($resultado);
		
				if (mysql_affected_rows()==0)
				{
					$ficheiro=$_FILES['foto'];
					$nome_final=$_POST['ref'] . "_foto.jpg";
				
					if ($ficheiro['error']==0)
					{
						if ( 
			    			in_array( $ficheiro['type'], array ( 'image/pjpeg', 'image/jpeg', 'image/png','image/gif' ) ) 
							)
						{
							@move_uploaded_file ($ficheiro['tmp_name'], 'foto/' . $nome_final);
							mysql_connect('localhost','root','');
							mysql_select_db('albino');
	}
	}}
	
	
	
	
	$sql="insert into produtos(marca, cor_principal, mat_fabrico, altura, largura, referencia, foto, descricao) values ('" .  $_POST['marca']  .  "','"  .  $_POST['cor']  .  "','"  .  $_POST['matfabrico']  .  "','" . $_POST['altura'] . "','" . $_POST['largura'] . "','" . $_POST['ref'] . "','" . $_POST['file'] . "','" . $_POST['descricao'] . "')";
	
	mysql_query($sql);
	echo "Produto inserido com sucesso! <br><a href='inserir_produto.php'>Voltar</a>";
	}
	
	else {
	echo "Erro! Verifique o formulário!<br><a href='inserir_produto.php'>Voltar</a>";
	}


?>

THE THING IS THAT THE IMAGE THAT I WANT TO UPLOAD IS NOT UPLOADING TO THE SPECIFIC FOLDER...THE ERROR THAT APPEARS ME IS THIS ONE:

Notice: Undefined index: foto in C:\wamp\www\A.S.S\inserir_produto1.php on line 28


CAN YOU HELP ME? IM FREAKING OUT WITH THIS...

I WOULD BE VERY APPRECIATED....

PS.: SORRY ABOUT MY ENGLISH, IM PORTUGUESE

:) As the error itself says, foto is undefined.

$ficheiro=$_FILES['foto'];

should be

$ficheiro=$_FILES['file'];

One more thing, notices are usually generated when you don't initialize a variable [and start using it]. Check out php.net -> error_reporting for more details.
Cheers,
Naveen

sir/mam,

I'm getting an undefined index error with the following code and I can't for the life of me figure out why. Any insight would be greatly appreciated.

I'm using an html form and a PHP file to upload images to a directory and write the rest of the form details to my DB. The images get uploaded to the directory just fine, but it's not writing the rest of the data to the DB for some reason.

<?php

$hotelname=$_REQUEST['hotelname'];  
$roomtype=$_REQUEST['roomtype'];
 $roomcategory=$_REQUEST['roomcategory'];
$inclusion=$_REQUEST['inclusion'];
 $price=$_REQUEST['price'];
 $roomdesc=$_REQUEST['roomdesc'];
 $amenities=$_REQUEST['amenities'];

 echo $photo=($_FILES['photo']['name']);

$status=$_REQUEST['status'];


 include_once('conn.php');

 $sql=" Insert into addhotel set  
 Hotel_name='$hotelname',
 Room_type='$roomtype',
 Room_category='$roomcategory',
 Inclusion='$inclusion',
 Charges='$price',

 Rooms_description='$roomdesc',
 Hotel_amenities='$amenities',
Hotel_image='$photo',
 Status='$status'";





$result=mysql_query($sql) or die ('Query Not Executed '.mysql_error());
if ($result)
{
    //pic();

    if (pic()==true)
    {
         echo "profile  updated............";

    }

}
else
{
    echo "profile not updated............";
}


function pic()
{
    if ((($_FILES["photo"]["type"] == "image/gif")
|| ($_FILES["photo"]["type"] == "image/jpeg")
|| ($_FILES["photo"]["type"] == "image/pjpeg"))
&& ($_FILES["photo"]["size"] > 20000)){

      if (move_uploaded_file($_FILES["photo"]["tmp_name"],
    "admin/upload/" . $_FILES["photo"]["name"]))
      {
        return true;
        exit();
      }
      else
      {
        return false;
      exit();
      }
    }
  else 
  {
    return false;
    exit();
}
}


mysql_close() ;

?>

thanks and regards brijeshwart tiwari

sir/mam,

I'm getting an undefined index error with the following code and I can't for the life of me figure out why. Any insight would be greatly appreciated.

I'm using an html form and a PHP file to upload images to a directory and write the rest of the form details to my DB. The images get uploaded to the directory just fine, but it's not writing the rest of the data to the DB for some reason.

<?php

$hotelname=$_REQUEST;
$roomtype=$_REQUEST;
$roomcategory=$_REQUEST;
$inclusion=$_REQUEST;
$price=$_REQUEST;
$roomdesc=$_REQUEST;
$amenities=$_REQUEST;

echo $photo=($_FILES);

$status=$_REQUEST;


include_once('conn.php');

$sql=" Insert into addhotel set
Hotel_name='$hotelname',
Room_type='$roomtype',
Room_category='$roomcategory',
Inclusion='$inclusion',
Charges='$price',

Rooms_description='$roomdesc',
Hotel_amenities='$amenities',
Hotel_image='$photo',
Status='$status'";

$result=mysql_query($sql) or die ('Query Not Executed '.mysql_error());
if ($result)
{
//pic();

if (pic()==true)
{
echo "profile updated............";

}

}
else
{
echo "profile not updated............";
}


function pic()
{
if ((($_FILES["photo"]["type"] == "image/gif")
|| ($_FILES["photo"]["type"] == "image/jpeg")
|| ($_FILES["photo"]["type"] == "image/pjpeg"))
&& ($_FILES["photo"]["size"] > 20000)){

if (move_uploaded_file($_FILES["photo"]["tmp_name"],
"admin/upload/" . $_FILES["photo"]["name"]))
{
return true;
exit();
}
else
{
return false;
exit();
}
}
else
{
return false;
exit();
}
}


mysql_close() ;

?>

geting error

Notice: Undefined index: photo in D:\wamp\www\budgethotelsdelhi.net\admin\addhotels.php on line 14

Notice: Undefined index: photo in D:\wamp\www\budgethotelsdelhi.net\admin\addhotels.php on line 57

Notice: Undefined index: photo in D:\wamp\www\budgethotelsdelhi.net\admin\addhotels.php on line 58

Notice: Undefined index: photo in D:\wamp\www\budgethotelsdelhi.net\admin\addhotels.php on line 59

hi I am student and trying to upload an image in the data base
I am getting an error


Notice: Undefined index: image in C:\xampp\www\display_img\TMP49d65v5y5t.php on line 17


I am using XAMPP and MacroMedia DreamWeaver 8

and my code is

<!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=iso-8859-1" />
<title>upload an image</title>
</head>

<body>
	
<form action="index.php" method="post" enctype="multipart/form-data">
	File:
	<input type="file" name="image"  /> <input type="submit" value="upload" />
</form>
<?php
	mysql_connect("localhost","root","") or die(mysql_error());
	mysql_select_db("databaseimage") or die(mysql_error());
	$file = $_FILES["image"]["tmp_name"];
?>
</body>
</html>
<?php
include_once 'db/db.php';
include_once 'admin-class.php';

//This is the directory where images will be saved
$target = 'images/upload/';
$target = $target . basename( $_FILES['photo']['name']);

//This gets all the other information from the form
$name=$_POST['name'];
$detail=$_POST['detail'];
$pic=($_FILES['photo']['name']);

// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("mdb_lh026") or die(mysql_error()) ;

//Writes the information to the database
mysql_query("INSERT INTO products (productname,detail,image) VALUES ('$name', '$detail', '$pic')") ;

//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

//Tells you if its all ok
echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory";
}
else {

//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}

?> 
<!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>Web Store Theme - Contact</title>
<meta name="keywords" content="web store, contact page, form, free templates, website templates, CSS, HTML" />
<meta name="description" content="Web Store Theme, Contact Form, free CSS template provided by templatemo.com" />
<link href="css/templatemo_style.css" rel="stylesheet" type="text/css" />

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

<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/ddsmoothmenu.js">

/***********************************************
* Smooth Navigational Menu- (c) Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

</script>

<script type="text/javascript">

ddsmoothmenu.init({
    mainmenuid: "templatemo_menu", //menu DIV id
    orientation: 'h', //Horizontal or vertical menu: Set to "h" or "v"
    classname: 'ddsmoothmenu', //class added to menu's outer DIV
    //customtheme: ["#1c5a80", "#18374a"],
    contentsource: "markup" //"markup" or ["container_id", "path_to_menu_file"]
})

function clearText(field)
{
    if (field.defaultValue == field.value) field.value = '';
    else if (field.value == '') field.value = field.defaultValue;
}
</script>

</head>

<body id="subpage">

<div id="templatemo_wrapper">
    <div id="templatemo_header">
        <div id="site_title"><h1><a href="http://www.templatemo.com">Free CSS Templates</a></h1></div>

        <div id="header_right">
            <ul id="language">
                <li><a><img src="images/usa.png" alt="English" /></a></li>
                <li><a><img src="images/china.png" alt="Chinese" /></a></li>
                <li><a><img src="images/germany.png" alt="Germany" /></a></li>
                <li><a><img src="images/india.png" alt="Indian" /></a></li>
            </ul>
            <div class="cleaner"></div>
            <div id="templatemo_search">
                <form action="#" method="get">
                  <input type="text" value="Search" name="keyword" id="keyword" title="keyword" onfocus="clearText(this)" onblur="clearText(this)" class="txt_field" />
                  <input type="submit" name="Search" value="" alt="Search" id="searchbutton" title="Search" class="sub_btn"  />
                </form>
            </div>
         </div> <!-- END -->
    </div> <!-- END of header -->

    <div id="templatemo_menu" class="ddsmoothmenu">
        <ul>
            <li><a href="index.php">Home</a></li>
            <li><a href="products.php">Products</a>
                <ul>
                    <li><a href="#">Sub menu 1</a></li>
                    <li><a href="#">Sub menu 2</a></li>
                    <li><a href="#">Sub menu 3</a></li>
              </ul>
            </li>
            <li><a href="about.php">About</a>
                <ul>
                    <li><a href="#">Sub menu 1</a></li>
                    <li><a href="#">Sub menu 2</a></li>
                    <li><a href="#">Sub menu 3</a></li>
                    <li><a href="#">Sub menu 4</a></li>
                    <li><a href="#">Sub menu 5</a></li>
              </ul>
            </li>
            <li><a href="faqs.html">FAQs</a></li>
            <li><a href="checkout.html">Checkout</a></li>
            <li><a href="contact.html" class="selected">Contact</a></li>
        </ul>
        <br style="clear: left" />
    </div> <!-- end of templatemo_menu -->

    <div class="cleaner h20"></div>
    <div id="templatemo_main_top"></div>
    <div id="templatemo_main">

        <div id="sidebar">
         <h3>Account Manager</h3>
            <ul class="sidebar_menu">
                <li><a href="editprofile.php">Edit Profile</a></li>
                <li><a href="#">Aenean pulvinar</a></li>                
                <li><a href="getimageform.php">Upload Product</a></li>
                <li><a href="editproduct.php">Edit Product</a></li>             

            </ul>
            <h3>Newsletter</h3>
            <p>Praesent aliquam mi id tellus pretium pulvinar in vel ligula.</p>
            <div id="newsletter">
                <form action="#" method="get">
                  <input type="text" value="Subscribe" name="email_newsletter" id="email_newsletter" title="email_newsletter" onfocus="clearText(this)" onblur="clearText(this)" class="txt_field" />
                  <input type="submit" name="subscribe" value="Subscribe" alt="Subscribe" id="subscribebtn" title="Subscribe" class="subscribebtn"  />
                </form>
                <div class="cleaner"></div>
            </div>
        </div> <!-- END of sidebar -->

        <div id="content">
            <h2>Upload Image</h2>

            <div class="col col_13">
            <p>Upload your product name, product image, & product detail here</p>
            <div id="contact_form">
               <form id="upload_form" name="upload_form" action="<?php echo $_SERVER['PHP_SELF']; ?>"  method="post" >

                    <label for="name">Product Name:</label> <input type="text" id="name" name="name" class="" />
                    <div class="cleaner h10"></div>
                    <input type="file" name="photo"/>
                    <div class="cleaner h10"></div>



                    <label for="detail">Detail:</label> <input type="text" name="detail" id="detail" class="" />
                    <div class="cleaner h10"></div>

                    <label for="text">Message:</label> <textarea id="text" name="text" rows="0" cols="0" class="">

i have try to look up for error but just couldnt find. Error of undefined index keep appearing. what must i change?Please help...

Notice: Undefined index: photo in /home/lh026/public_html/webstore/getimageform.php on line 7

Notice: Undefined index: name in /home/lh026/public_html/webstore/getimageform.php on line 10

Notice: Undefined index: detail in /home/lh026/public_html/webstore/getimageform.php on line 11

Notice: Undefined index: photo in /home/lh026/public_html/webstore/getimageform.php on line 12

Notice: Undefined index: photo in /home/lh026/public_html/webstore/getimageform.php on line 22
Sorry, there was a problem uploading your file.

Next time please start a new discussion.

The values you are using on those lines do not have a value the first time the page is opened. You'll need to use this construct:

if (isset($_FILES['photo'])) {
    // upload file code
}

hi, i found this thread and same problem with dottom, sorry but im bit slow to pick up the correct solution what nav33n answered "$_FILES". hope u can still help. thanks in advance.

i think i have the answer, but am not sure if this is the correct one.
basename( $_FILES['photo']['name']) instead of basename( $_FILES['uploadedfile']['name'])

thanks again.

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.