...

View Full Version : dropdown menu issue



saunders1989
01-17-2010, 02:43 PM
i just pasted this code to validate it using the w3c validator but i get a fair amount of errors with the coloured section:

i know if i change it to <option>Please select a gallery</option> and then have the php code below i get the writing first and then my selections after but if the user accidently doesnt select a gallery it would upload the file to the database and give the gallery id=0 which there isnt a gallery which corrosponds to the number 0 so i dont know why it doesnt validate or weather or not i have to have the writing first but then validate it to choose one of the gallerys somehow but i dont know how to validate a dropdown menu

thanks


<!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>
<?php


$dbLink = new mysqli('localhost', 'root', '', 'gallery');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}

$query = "SELECT gallery_type_id, gallery_type_desc FROM gallery_type ORDER BY gallery_type_id";

/* run the query */
$result = $dbLink->query($query);

/* load the query's results into an array */
$i=1;
while($row=$result->fetch_assoc()){
$galleryTypes[$i] = $row;
$i++;
}
$num_results = $result->num_rows;
?>

</head>

<body>

<form action="add_file.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="5242880" />
<input type="file" name="uploaded_file" /><br />
<input type="submit" value="Upload file" />
<label for="gallery_type">Gallery Type</label>
<select name="gallery_type" id="gallery_type">
<option value="<?php
for($i = 1; $i < $num_results+1; $i++) {
echo "<option value=\"" . $galleryTypes[$i]['gallery_type_id'] . "\">";
echo $galleryTypes[$i]['gallery_type_desc'];
echo "</option>\n";
}
?>"
</option>
</select>
</form>

</body>
</html>

Dormilich
01-17-2010, 04:12 PM
i just pasted this code to validate it using the w3c validator but i get a fair amount of errors with the coloured section:
right, it doesn’t make sense to define option elements inside an option value.


but if the user accidently doesnt select a gallery it would upload the file to the database and give the gallery id=0 which there isnt a gallery which corrosponds to the number 0 so i dont know why it doesnt validate or weather or not i have to have the writing first but then validate it to choose one of the gallerys somehow but i dont know how to validate a dropdown menu

on the PHP side, check for that "unselected" value before processing further. on the client side, you can make a JavaScript, that tells the user he hasn’t selected a gallery and cancel the submit.

bdl
01-17-2010, 04:13 PM
If you're attempting to validate the markup that this script outputs, please post the actual markup (HTML source from your browser or from the validator output) so we can evaluate what PHP is actually doing and correct. The validator doesn't care what PHP is doing.

Fou-Lu
01-17-2010, 04:16 PM
W3 validation has nothing to do with PHP aside from potentially poor form/anchor elements.
If you're asking for how to validate it with php, you'd simply check to see if $_POST['gallery_type'] is an acceptable value with php prior to any insertions into you're database. If not, inform the user and send them back. You can also avoid this by using optgroup with a label in you're selection menu, but since optgroups are non-selectable you have to provide a default gallery to choose from.

As for you're actual HTML building, option cannot have a value of another option. This would be an optgroup:


<optgroup label="Please Select">
<?php
for($i = 1; $i < $num_results+1; $i++) {
echo "<option value=\"" . $galleryTypes[$i]['gallery_type_id'] . "\">";
echo $galleryTypes[$i]['gallery_type_desc'];
echo "</option>\n";
}
?>"
</optgroup>


This will not show in the selection menu for a default option though, an actual gallery reference would be displayed insted - the first one if no selected value is provided.
A solution to this would be to use a list box style instead of the combo box by setting the select size > 1.

saunders1989
01-17-2010, 04:41 PM
thanks for you replys. could you please explain in a little more detail about the server side about checking if the dropdown menu has been changed to the right one please as i am new to this i dont really understand how?

i did try your optgroup method and thanks for showing me that i never knew about them until you said it. it does seem like a good idea and would work in my case but if i wanted to be strict on validation i would advise the user to select a gallery as i previously had it and then do checks to see if a gallery has been selected.

could you please advise how to go about that

Thanks!

Dormilich
01-17-2010, 04:50 PM
i did try your optgroup method and thanks for showing me that i never knew about them until you said it. it does seem like a good idea and would work in my case but if i wanted to be strict on validation i would advise the user to select a gallery as i previously had it and then do checks to see if a gallery has been selected.

give the "heading" a value (e.g. 0) and test for that specific value in your script


if ("0" == $_POST["gallery_type"])
{
throw new Exception("No gallery selected.");
// die("No gallery selected.");
}

EDIT: throwing an Exception is a comfortable way of handling errors. ref. Exception (http://php.net/exception). it allows you to "jump" over code (which is then not executed) until it finds a catch directive, that can handle the error.

simple example

try
{
if ("0" == $_POST["gallery_type"])
{
throw new Exception("No gallery selected.");
}
// insert file into DB
}
catch (Exception $e)
{
// load the form again with an error message
header("Location: upload.php?errmsg=" . urlencode($e->getMessage()));
exit;
}
note: the most noteable advantage of exceptions is, that they provide you with a lot of information (file/line no. thrown in, time, a stacktrace, etc.)

saunders1989
01-17-2010, 10:19 PM
hi. i dont understand how that fits around my code

<?php
for($i = 1; $i < $num_results+1; $i++) {
echo "<option value=\"" . $galleryTypes[$i]['gallery_type_id'] . "\">";
echo $galleryTypes[$i]['gallery_type_desc'];
echo "</option>\n";
}
?>

i am very new to php so please could you explain quite simple how i would fit it around it

thanks

Dormilich
01-18-2010, 06:54 AM
you mean the Exceptions?

saunders1989
01-18-2010, 04:37 PM
yer the exceptions. not totally sure how it would all work

Dormilich
01-18-2010, 06:24 PM
the Exceptions are not meant to work with the <option> code. itís meant to aid you when testing whether a valid gallery type has been submitted.


try
{
if ("0" == $_POST["gallery_type"])
{
throw new Exception("No gallery selected.");
}
// connect to DB
for ($i = 1; $i <= $num_results; $i++)
{
echo "<option value=\"", $galleryTypes[$i]['gallery_type_id'], "\">";
echo $galleryTypes[$i]['gallery_type_desc'];
echo "</option>\n";
}
}
catch (Exception $e)
{
header("Location: upload.php?errmsg=" . urlencode($e->getMessage()));
exit;
}

Fou-Lu
01-18-2010, 06:45 PM
This being said, exceptions are of little use in a procedural fashion. Its silly to throw and catch when you can simply validate:


if (0 == $_POST['gallery_type'])
{
header('Location: http://mysite.com/upload.php?errmsg=' . urlencode('No gallery selected'));
exit;
}

for ($i = 0; i <= $num_results; ++$i)
{
...


Exceptions are more useful in an OO approach (or a very well designed chained function handling) to programming over a procedural one. Since you have no idea what code is handling you're classes, exceptions are the easiest way to tell them that invalid, failed, problematic, etc data has been submitted without concerning yourself on the implementation details of the class or object.

Dormilich
01-18-2010, 07:10 PM
I just felt like introducing Exceptions Ö

saunders1989
01-18-2010, 07:34 PM
if these dont work with options how do i get a dropdown menu validated then?

i have as my first option just text. saying 'please select a gallery'
the following options are generated from the for statement. but that exception wouldnt work.

so for example

please select a gallery
war - id in database is 1
buildings - id in databse is 2
church - id in database is 3

if i forge to select a gallery my image is uploaded with the id of 0 which will not display it on the correct page.

Dormilich
01-18-2010, 07:48 PM
use Fou-Luís code

saunders1989
01-18-2010, 08:01 PM
i tried that but i dont understand the header line.

the website address is 'http://localhost/Blean_Photos/upload.php'

and if i put this code. i dont get the .urlencode part. i dont think it would work


if (0 == $_POST['gallery_type'])
{
header('Location: 'http://localhost/Blean_Photos/upload.php' . urlencode('No gallery selected'));
exit;
}

for ($i = 0; i <= $num_results; ++$i)
{
...

Fou-Lu
01-18-2010, 08:19 PM
I just felt like introducing Exceptions …

And don't get me wrong, exceptions are the greatest thing since sliced bread. But using exceptions where not really needed is kinda like killing a squirrel with a cannon.


This is incorrect for the header, you have a string break right inside you're url:


header('Location: 'http://localhost/Blean_Photos/upload.php' . urlencode('No gallery selected'));

This should be:


header('Location: http://localhost/Blean_Photos/upload.php?errmsg=' . urlencode('No gallery selected'));

Then you gracefully handle the errmsg passed to upload.php. I'd actually go back to wherever you're form is, and simply check first if an error exists to show a nice message to the user.
The localhost may not work as expected. For the most part, you can usually get away with using Location: mypage.php as you're redirection header, but it should be noted that the specification indicates that the location header should include the complete uri.

Dormilich
01-18-2010, 08:28 PM
And don't get me wrong, exceptions are the greatest thing since sliced bread. But using exceptions where not really needed is kinda like killing a squirrel with a cannon.

yes, youíre right, but I couldnít resist.

saunders1989
01-18-2010, 08:35 PM
i changed my header to your header but now a page doesnt even load
this is the address:
'http://localhost/Blean_Photos/upload.php?errmsg=No+gallery+selected'

firefox is saying the page isnt redirecting properlly.

thats what i would like it to do is return to my upload.php page and say the the user please select a gallery before uploading.

Fou-Lu
01-18-2010, 08:55 PM
i changed my header to your header but now a page doesnt even load
this is the address:
'http://localhost/Blean_Photos/upload.php?errmsg=No+gallery+selected'

firefox is saying the page isnt redirecting properlly.

thats what i would like it to do is return to my upload.php page and say the the user please select a gallery before uploading.

Its likely then that upload.php is referring to this actual script. The redirection fails since it is creating an infinite redirect cycle.
Redirect the user back to the original page that handles the form.

saunders1989
01-18-2010, 09:08 PM
i changed the address to just:

'http://localhost/Blean_Photos/upload.php'

but get this weird error: as if it is doing what it says its doing and just looping infinatly. but i wouldnt know how to stop it.

Firefox has detected that the server is redirecting the request for this address in a way that will never complete.

the php code looks as follows:


<?php
if (0 == $_POST['gallery_type'])
{
header('Location: http://localhost/Blean_Photos/upload.php');
exit;
}

for($i = 1; $i < $num_results+1; $i++) {
echo "<option value=\"" . $galleryTypes[$i]['gallery_type_id'] . "\">";
echo $galleryTypes[$i]['gallery_type_desc'];
echo "</option>\n";
}
?>

Fou-Lu
01-18-2010, 11:13 PM
Yes, thats because this script is upload.php. Change it to go to myinputform.php instead (or whatever you're script name is for the input form).

saunders1989
01-18-2010, 11:49 PM
well the page i am on is called upload.php. i want the user to be redirected to the exact same page upload.php if there is an error. but that doesnt work.

also i tried changing the header to a different page but the page upload.php doesnt appear.

i also did attempt the code with a different header and was still able to upload the image without selecting a gallery

this is the whole code for my upload.php


<!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>
<?php


$dbLink = new mysqli('localhost', 'root', '', 'gallery');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}

$query = "SELECT gallery_type_id, gallery_type_desc FROM gallery_type ORDER BY gallery_type_id";

/* run the query */
$result = $dbLink->query($query);

/* load the query's results into an array */
$i=1;
while($row=$result->fetch_assoc()){
$galleryTypes[$i] = $row;
$i++;
}
$num_results = $result->num_rows;

?>
</head>

<body>

<form action="add_file.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="5242880" />
<input type="file" name="uploaded_file" /><br />
<input type="submit" value="Upload file" />
<label for="gallery_type">Gallery Type</label>
<select name="gallery_type" id="gallery_type">
<option>Please select a gallery
<?php
for($i = 1; $i < $num_results+1; $i++) {
echo "<option value=\"" . $galleryTypes[$i]['gallery_type_id'] . "\">";
echo $galleryTypes[$i]['gallery_type_desc'];
echo "</option>\n";
}
?>
</option>
</select>
</form>

</body>
</html>

Fou-Lu
01-19-2010, 12:42 AM
Oh oh, no no you misunderstand where to put the validation.
All validation for this will occur in the add_file.php script. That script you can redirect back to upload.php, and thats where you should be putting you're check to see if $_POST['gallery_type'] is an acceptable value.

saunders1989
01-19-2010, 12:46 AM
oh wow. sorry my bad. very new to php. i now have got that working. thanks for clearing that one up.

how would i make sure it displays a nice little message saying please choose a gallery?

Dormilich
01-19-2010, 07:02 AM
in the HTML script (in a nice place) do something like

if (isset($_GET["errmsg"]))
{
// of course you have to create the CSS for this class too
echo '<div class="error">', $_GET["errmsg"], '</div>';
}

saunders1989
01-19-2010, 10:58 AM
can you explain where i get errmsg from? i havent declared that anywhere. would i declare that in the add_file.php where i do my validation?

Dormilich
01-19-2010, 11:01 AM
it comes from

header('Location: http://localhost/Blean_Photos/upload.php?errmsg=' . urlencode('No gallery selected'));

saunders1989
01-19-2010, 01:50 PM
so this code is essentially taking me to another page i would have to create to display please select a gallery? as no text is displayed on my upload form if i dont select a gallery.

if i just want it to echo 'please select a gallery' on the upload form would i change the echo of $_GET to just please select a gallery?

Dormilich
01-19-2010, 01:56 PM
that is the page you started with. (though I donít remember all their names)

saunders1989
01-19-2010, 01:59 PM
no text is actually displayed when no gallery is selected only the url is changed

Fou-Lu
01-19-2010, 03:00 PM
Can you post all of you're code for upload.php and add_file.php?
This way we can show you what you need to change to do what you're looking to do.

saunders1989
01-19-2010, 03:13 PM
sure. thanks for sticking at this for me.

upload.php:


<!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>
<?php


$dbLink = new mysqli('localhost', 'root', '', 'gallery');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}

$query = "SELECT gallery_type_id, gallery_type_desc FROM gallery_type ORDER BY gallery_type_id";

/* run the query */
$result = $dbLink->query($query);

/* load the query's results into an array */
$i=1;
while($row=$result->fetch_assoc()){
$galleryTypes[$i] = $row;
$i++;
}
$num_results = $result->num_rows;

?>
</head>

<body>

<form action="add_file.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="5242880" />
<input type="file" name="uploaded_file" /><br />
<input type="submit" value="Upload file" />
<label for="gallery_type">Gallery Type</label>
<select name="gallery_type" id="gallery_type">
<option>Please select a gallery
<?php
for($i = 1; $i < $num_results+1; $i++) {
echo "<option value=\"" . $galleryTypes[$i]['gallery_type_id'] . "\">";
echo $galleryTypes[$i]['gallery_type_desc'];
echo "</option>\n";
}

if (isset($_GET["errmsg"]))
{
// of course you have to create the CSS for this class too
echo '<div class="error">', $_GET["errmsg"], '</div>';
}

?>
</option>
</select>
</form>

</body>
</html>

add_file.php:


<!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>
</head>

<body>

<?php

$max_size=5*1024*1024;

// Check if a file has been uploaded
if(isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['size']<= $max_size)
{
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
$target_path = "images/";
$target_path = $target_path . basename( $_FILES['uploaded_file']['name']);

if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path) && !file_exists( $target_path) ) {
echo "The file ". basename( $_FILES['uploaded_file']['name']).
" has been uploaded";

$dbLink = new mysqli('localhost', 'root', '', 'gallery');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}

// Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
$size = intval($_FILES['uploaded_file']['size']);
$image_path = $dbLink->real_escape_string($target_path);
$gallery_type = $dbLink->real_escape_string($_POST['gallery_type']);

//query to insert the data i had gathered into the database
$query = "INSERT INTO `images` (`name`, `size`, `created`, `image_path`, `gallery_type_id`)
VALUES ('{$name}', {$size}, NOW(), '{$image_path}', '{$gallery_type}')";

//executes the query
$dbLink->query($query);
}
}
else {
echo 'Error! A file was not sent!';
}
}

else {
echo 'The file is too large';
}

if (0 == $_POST['gallery_type'])
{
header('Location: http://localhost/Blean_Photos/upload.php?errmsg=' . urlencode('No gallery selected'));
exit;
}

// Echo a link back to the main page
echo '<p>Click <a href="member-index.php">here</a> to go back</p>';
?>

</body>
</html>

Fou-Lu
01-19-2010, 04:27 PM
This one won't be too bad:


<!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>
<?php


$dbLink = new mysqli('localhost', 'root', '', 'gallery');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}

$query = "SELECT gallery_type_id, gallery_type_desc FROM gallery_type ORDER BY gallery_type_id";

/* run the query */
$result = $dbLink->query($query);

/* load the query's results into an array */
$i=1;
while($row=$result->fetch_assoc()){
$galleryTypes[$i] = $row;
$i++;
}
$num_results = $result->num_rows;

?>
</head>

<body>
<?php

if (isset($_GET["errmsg"]) && !empty($_GET['errmsg']))
{
// of course you have to create the CSS for this class too
echo '<div class="error">', $_GET["errmsg"], '</div>';
}
?>


<form action="add_file.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="5242880" />
<input type="file" name="uploaded_file" /><br />
<input type="submit" value="Upload file" />
<label for="gallery_type">Gallery Type</label>
<select name="gallery_type" id="gallery_type">
<option value="0">Please select a gallery</option>
<?php
for($i = 1; $i < $num_results+1; $i++) {
echo "<option value=\"" . $galleryTypes[$i]['gallery_type_id'] . "\">";
echo $galleryTypes[$i]['gallery_type_desc'];
echo "</option>\n";
}
?>
</select>
</form>

</body>
</html>


I haven't gone through the add_file at all, but from the sounds of it there is no issue there. I just made sure the header redirect was going to the right place and had the string you expected.


Yeah no the add_file.php is wrong too. The location won't give you any benefit:


<!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>
</head>

<body>

<?php

$max_size=5*1024*1024;

// I figure no point in letting the file move unless the gallery has been chosen:
if (0 == $_POST['gallery_type'])
{
header('Location: http://localhost/Blean_Photos/upload.php?errmsg=' . urlencode('No gallery selected'));
exit;
}

// Check if a file has been uploaded
if(isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['size']<= $max_size)
{
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
$target_path = "images/";
$target_path = $target_path . basename( $_FILES['uploaded_file']['name']);

if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path) && !file_exists( $target_path) ) {
echo "The file ". basename( $_FILES['uploaded_file']['name']).
" has been uploaded";

$dbLink = new mysqli('localhost', 'root', '', 'gallery');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}

// Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
$size = intval($_FILES['uploaded_file']['size']);
$image_path = $dbLink->real_escape_string($target_path);
$gallery_type = $dbLink->real_escape_string($_POST['gallery_type']);

//query to insert the data i had gathered into the database
$query = "INSERT INTO `images` (`name`, `size`, `created`, `image_path`, `gallery_type_id`)
VALUES ('{$name}', {$size}, NOW(), '{$image_path}', '{$gallery_type}')";

//executes the query
$dbLink->query($query);
}
}
else {
echo 'Error! A file was not sent!';
}
}

else {
echo 'The file is too large';
}

// Echo a link back to the main page
echo '<p>Click <a href="member-index.php">here</a> to go back</p>';
?>

</body>
</html>

saunders1989
01-19-2010, 05:09 PM
what do you mean the location wont be any benifit?

is there a way to do what ive done with my other validation just produce a echo saying select the gallery? like the file is too large or a file wasnt sent?

EDIT:

this code (below) interupts with the file too large error message. if the file is too large this kicks in instead of displaying the error message i have. but if i take it out i get the error i want when i upload a file larger than the max size

if (0 == $_POST['gallery_type'])
{
header('Location: http://localhost/Blean_Photos/upload.php?errmsg=' . urlencode('No gallery selected'));
exit;
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum