Jump to content

Any suggestions?


haris244808

Recommended Posts

what i want is to upload my informations to database when i press the submit button.

but if any field is empty it should show a text that all fields are required but in the same page(up or down to the form).

However with this code my database is not working>informations are not send to the database.

why?Any sggesstions?

 

<?php 
// Start a session for error reporting
session_start();
//Connect to database
require("includes/connect_to_mysql.php");

//check if the button is pressed
if(isset($_POST['submit'])){
// 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", "image/png");


	if (in_array($file['type'], $valid_types))
		return 1;
	    return 0;
}
// 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 = "upload_form_images/";

// Get our POSTed variables
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$city = $_POST['city'];
$details = $_POST['details'];
$price = $_POST['price'];
$image = $_FILES['image'];

// Sanitize our inputs
$name = mysql_real_escape_string($name);
$surname = mysql_real_escape_string($surname);
$email = mysql_real_escape_string($email);
$city = mysql_real_escape_string($city);
$details = mysql_real_escape_string($details);
$price = mysql_real_escape_string($price);
$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 ( $name == "" || $surname == "" || $email == "" || $city == ""  || $details == "" || $price == ""|| $image['name'] == "" )
{
	$_SESSION['error'] = "Te gjithe fushat duhet plotesuar";
	echo "Te gjithe fushat duhet plotesuar";
	header("Location: upload_form.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'] = "Fotografite duhet te jene te formateve jpg, jpeg, bmp, gif, ose png";
	header("Location: upload_form.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'] = "Ju lutem nderroni emrin e fotos.";
	header("Location: upload_form.php");
	exit;
}

	/*
	// See if that product name is an identical match to another product in the system
	$sql = mysql_query("SELECT id FROM upload_form WHERE name='$name' LIMIT 1");
	$productMatch = mysql_num_rows($sql); // count the output amount
    if ($productMatch > 0) {
		$_SESSION['error'] = 'Ju lutem nderroni emrin sepse egziston ne databaze';
		header("Location: upload_form.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 (name, surname, email, city, details, price, filename) values ('$name', '$surname', '$email', '$city', '$details', 		'$price', '" . $image['name'] . "')";
	$result = mysql_query($sql) or die ("Futja e te dhenave ne databaze DESHTOI: " . mysql_error());
	echo "Shtimi i te dhenave u krye me SUKSES";
	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'] = "Shtimi i te dhenave NUK u krye me Sukses.  Ju lutem provoni perseri";
	header("Location: upload_form.php");
	exit;
}
}
?>

<!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>Qiraja.com</title>
<link rel="stylesheet" href="css/style.css" type="text/css" media="all" />
<!--[if lte IE 6]><link rel="stylesheet" href="css/ie6.css" type="text/css" media="all" /><![endif]-->
<!--[if IE]><style type="text/css" media="screen"> #navigation ul li a em { top:32px; } </style><![endif]-->


</head>
<body>

<!-- Header -->
<div id="header">
<div class="shell">

	<!-- Logo -->
	<h1 id="logo"><a href="#">Company Name</a></h1>
	<!-- End Logo -->

	<!-- Navigation -->
	<div id="navigation">

		<ul>
		    <li><a href="#">Prishtine<span><em></em></span></a></li>
		    <li><a href="#">Prizren<span><em></em></span></a></li>
			<li><a href="#">Ferizaj<span><em></em></span></a></li> 
		    <li><a href="#">Peje<span><em></em></span></a></li>
			<li><a href="#">Mitrovice<span><em></em></span></a></li>
			<li><a href="#">Gjilan<span><em></em></span></a></li>
		    <li class="last"><a href="#">Gjakove<span><em></em></span></a></li>

		</ul>
	</div>  	
</div>
</div>


<div id="slider">
<div class="shell">

	<!-- Slides -->
	<div class="slides">
		<ul>
			<!-- Slide -->
		    <li>
                
                
<form action="upload_form.php" enctype="multipart/form-data" name="myForm" id="myform" method="post">
    <table width="90%" border="0" cellspacing="0" cellpadding="6">
      <tr>
        <td width="20%" align="center">Name</td>
        <td width="80%"><label>
          <input name="name" type="text" id="name" size="25" />
        </label></td>
      </tr>
      <tr>
        <td align="center">Surname</td>
        <td><label>
          <input name="surname" type="text" id="surname" size="25" />
        </label></td>
      </tr>
       <tr>
        <td align="center">Email</td>
        <td><label>
          <input name="email" type="text" id="email" size="25" />
        </label></td>
      </tr>
      <tr>
        <td align="center">City</td>
        <td><select name="city" id="city">
        <option value=""></option>
          <option value="Prishtine">Prishtine</option>
          <option value="Prizren">Prizren</option>
          <option value="Ferizaj">Ferizaj</option>
          <option value="Peje">Peje</option>
          <option value="Mitrovice">Mitrovice</option>
          <option value="Gjilan">Gjilan</option>
          <option value="Gjakove">Gjakove</option>
          </select></td>
      </tr>
      <tr>
        <td align="center">Cmimi</td>
        <td><label>
          <input name="price" type="text" id="price" size="10" />
          €
        </label></td>
      </tr>
      <tr>
        <td align="center">Fotografite</td>
        <td><label>
          <input type="file" name="image" id="image" />
        </label></td>
      </tr>      
      <tr>
        <td> </td>
        <td align="right"><label>
        	<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
          <input type="submit" name="submit" id="submit" value="Shto te dhenat" />
        </label></td>
      </tr>
    </table>
    </form>

		    </li>
		    <!-- End Slide -->
		    
		    <!-- Slide -->
		    <li>
		    	<div class="slide-info">
			    	<h2><span>Reklamo</span> Shtepine</h2>
			    	<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam arcu ligula, faucibus eu imperdiet eu, bibendum sit amet augue. Sed turpis sem, interdum sit amet egestas a, mattis non libero. Suspendisse tristique nisi sed justo accumsan vel mattis nulla fermentum. Etiam varius est id mi fermentum aliquam.</p>
			    	<p>Quisque quis vestibulum turpis. Sed venenatis ipsum laoreet elit pulvinar vitae pharetra massa dignissim. Curabitur ligula sapien, auctor ut porttitor a, ultricies lobortis dui. Suspendisse lacinia tellus a diam rutrum rhoncus. </p>

					<a href="#" class="more">read more</a></p>
		    	</div>
		    	<span class="slide-image image1"></span>
		    </li>
		    <!-- End Slide -->
		    
		    <!-- Slide -->
		    <li>
		    	<div class="slide-info">
			    	<h2><span>Reklamo</span> Apartmanin</h2>
			    	<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam arcu ligula, faucibus eu imperdiet eu, bibendum sit amet augue. Sed turpis sem, interdum sit amet egestas a, mattis non libero. Suspendisse tristique nisi sed justo accumsan vel mattis nulla fermentum. Etiam varius est id mi fermentum aliquam.</p>
			    	<p>Quisque quis vestibulum turpis. Sed venenatis ipsum laoreet elit pulvinar vitae pharetra massa dignissim. Curabitur ligula sapien, auctor ut porttitor a, ultricies lobortis dui. Suspendisse lacinia tellus a diam rutrum rhoncus. </p>

					<a href="#" class="more">read more</a></p>
		    	</div>
		    	<span class="slide-image image1"></span>
		    </li>
			<!-- End Slide -->
		    
	    </ul>
	</div>
	<!-- End Slides -->

</div>
</div>
<!-- End Slider -->

<!-- Slider Nav -->
<div id="slider-navigation">
<div class="shell">
	<ul>
	    <li><a href="index.php" class="active">Kthehu ne fillim<strong>Home</strong><em class="ico1"></em></a></li>
	    <li><a href="upload_form.php">Shto<strong>Upload</strong><em class="ico2"></em></a></li>
	    <li class="last"><a href="contact_form.php">Kontakti<strong>Contact</strong><em class="ico3"></em></a></li>
	</ul>
</div>
</div>
<!-- End Slider Nav -->

<!-- Main -->
<div id="main">
<div class="shell">

	<!-- Cols -->
	<div class="cols">
		<div class="cl"> </div>

		<!-- Col -->
		<div class="col">
			<h3>Sed Turpis sem</h3>
			<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam arcu ligula, faucibus eu imperdiet eu, bibendum sit amet augue. Sed turpis sem, interdum sit amet egestas a, mattis non libero.<br /><a href="#" class="more">read more</a></p>
			<p>Suspendisse tristique nisi sed justo accumsan vel mattis nulla fermentum. Etiam varius est id mi fermentum aliquam. <br /><a href="#" class="more">read more</a></p>
		</div>
		<!-- End Col -->

		<!-- Col -->
		<div class="col">
			<h3>Ligula amet augue</h3>
			<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam arcu ligula, faucibus eu imperdiet eu, bibendum sit amet augue. <br /><a href="#" class="more">read more</a></p>
			<p>Sed turpis sem, interdum sit amet egestas a, mattis non libero. Suspendisse tristique nisi sed justo accumsan vel mattis nulla fermentum. Etiam varius est id mi fermentum aliquam. <br /><a href="#" class="more">read more</a></p>
		</div>
		<!-- End Col -->

		<!-- Col -->
		<div class="col col-last">
			<h3>Ligula amet augue</h3>
			<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam arcu ligula, faucibus eu imperdiet eu, bibendum sit amet augue. <br /><a href="#" class="more">read more</a></p>
			<p>Sed turpis sem, interdum sit amet egestas a, mattis non libero. Suspendisse tristique nisi sed justo accumsan vel mattis nulla fermentum. Etiam varius est id mi fermentum aliquam. <br /><a href="#" class="more">read more</a></p>
		</div>
		<!-- End Col -->

		<div class="cl"> </div>
	</div>
	<!-- End Cols -->

</div>
</div>


</body>
</html>

Link to comment
Share on other sites

haris, are you getting any error messages, either MySQL errors or anything in your error log file?

 

where does $file come from ? (did you mean $_FILES ?)

 

$file is just the argument name. The variable given as the argument is $image which is set as:

 

$image = $_FILES['image'];

 

 

Link to comment
Share on other sites

yeah $file is only used in function declaration, he passes the $_FILES -array as parameter later to that function. I would start debugging from the if's echo something inside the IF where you run the query and see if the script ever goes inside it. If it doesn't then next you would debug the variables in the condition for what they contain. If they don't contain what you expect them to be, then you debug further why that happens.

Link to comment
Share on other sites

By adding an echo statement before your header() redirect, all you have done is create a header error (which you would see if you had error_reporting set to E_ALL and display_errors set to ON.) That has solved nothing.

 

When a validation error occurs, you don't want to redirect. You want your code to continue executing and redisplay the form with any validation error messages. In fact, you want to validate all the data at once and display all the validation errors at once. What you are doing now would only display the first error found, requiring the visitor to keep resubmitting the form for each piece of invalid data.

Link to comment
Share on other sites

By adding an echo statement before your header() redirect, all you have done is create a header error (which you would see if you had error_reporting set to E_ALL and display_errors set to ON.) That has solved nothing.

 

When a validation error occurs, you don't want to redirect. You want your code to continue executing and redisplay the form with any validation error messages. In fact, you want to validate all the data at once and display all the validation errors at once. What you are doing now would only display the first error found, requiring the visitor to keep resubmitting the form for each piece of invalid data.

 

so how i would have to solve this

Link to comment
Share on other sites

(I've seen this code before. Didn't you just mark this very same thing as SOLVED so you could post it again?)...

 

I recall asking you specifically to remove the redirects and do echo's instead, so we could find the error....

 

yes i posted before also but for another error and i thought its ok. but now i am faced with this error so i posted again :)

hoever let my try echo and see what is the error

Link to comment
Share on other sites

ok, that's a start. It basically means $_POST['details'] is not defined.

 

hahha what a mistake..

i forgot it ... yes i now added the details

but now when i press submit button it redirects to the blank page and ads nothing to database..

 

i just whant to add my infos to database when the submit button is pressed.

if any field is empty echo message that u need to write all fields (but this echo it will be in the same page up to the form or next to the form whatevr.)

Link to comment
Share on other sites

So what's up now? What debug you have done? Any errors? Suggestions to what?

 

now when i press submit button it redirects to the blank page and ads nothing to database..

 

i just whant to add my infos to database when the submit button is pressed.

if any field is empty echo message that u need to write all fields (but this echo it will be in the same page up to the form or next to the form whatevr.)

Link to comment
Share on other sites

The following pseudo code shows how you can put a form and form processing code on one page -

 

<?php

// check if your form was submitted
if(isset($_POST['submit'])){
$errors = array(); // use an array to both hold validation errors and to serve as a flag that there were validation errors
// put your code that conditions and validates the form data here...

// Each validation error sets an element in the $errors array -
if(empty($_POST['name'])){
	$errors[] = "Name was empty!";
}

// more validation tests here...

// done validating all the form data, check if there were any errors
if(empty($errors)){
	// no validation errors, use the form data here...

	// the form data has been successfully and completely processed
	header("Location: {$_SERVER['SCRIPT_NAME']}"); // redirect to the base page to clear the form data
	exit;
}
} // end of form processing code

// at this point, either the form has not been submitted or it has and there were validation errors
// produce any error content
if(!empty($errors)){
$error_content = "Please correct the following:<br />";
foreach($errors as $error){
	$error_content .= "$error<br />";
}
}

// produce your form, with any previously submitted data in the fields so that the visitor does not need to reenter it
// I recommend building your form in a variable, so that you can just output it later in your html page
$form_content = "
<form method='post' action='{$_SERVER['SCRIPT_NAME']}'>
<input type='text' name='name' value='". (isset($_POST['name']) ? htmlentities($_POST['name'],ENT_QUOTES) : '') ."'>
<input type='hidden' name='submit'>
<input type='submit'>
</form>";

?>
<!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>
</head>
<body>
other content here...

<?php echo isset($error_content) ? $error_content : ''; // display any errors that occured ?>

<?php echo isset($form_content) ? $form_content : ''; // output the form here ?>

other content here...
</body>
</html>

Link to comment
Share on other sites

  • 3 weeks later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.