Form not working properly

Hi folks,

I have this form which is supposed to collect exhibition info, artists, etc. It works fine except that it don’t insert the first name in the ‘artist’ and ‘curator’ tables. If I tries to insert three names in each field it inserts no. 2 and 3 together with all the exhibit id’s.
It looks i.e. like this in the table:
id - name - exhibitid
(6) - text2 - 22
(7) - text3 - 22
(8) - [blank] - 22

Here is my form code:


<?php include 'accesscontrol.php'; ?>     
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Legg til en utstilling</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<link href="default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="addtwofields.js"></script>
<script type="text/javascript" src="addtwofields2.js"></script>
<script type="text/javascript" src="CalendarPopup.js"></script>
</head>
<body>
<?php

if (isset($_POST['title'])): 
  // En utstilling har blitt lagt til
  // via denne formen.

$r = mysql_query("SHOW TABLE STATUS LIKE 'exhibit' ");
$row = mysql_fetch_array($r);
$Auto_increment = $row['Auto_increment'];
mysql_free_result($r);
$exid = $Auto_increment;


  $title = $_POST['title'];
  $start = $_POST['start_date'];
  $end = $_POST['end_date'];

  $sql = "INSERT INTO exhibit SET
      title='$title',
      start_date='$start',
      end_date='$end',
      date=LOCALTIMESTAMP(),
      galleryid='$gid'";
  if (@mysql_query($sql)) {
    echo '<p>En utstilling er lagt til</p>';
  } else {
    exit('<p>Feil ved innlegging av utstilling: ' . mysql_error() . '</p>');
  }

if(count($_POST))
{
	$len = count($_POST['aname']);
	for ($i=1; $i < $len; $i++)
	{

  $aname = $_POST['aname'][$i];

  $sql2 = "INSERT INTO artist SET
      aname='$aname',
      exhibitid='$exid'";
  if (@mysql_query($sql2)) {
    echo '<p>En kunstner er lagt til</p>';
  } else {
    exit('<p>Feil ved innlegging av kunstner: ' . mysql_error() . '</p>');
  }
	}
}

if(count($_POST))
{
	$len = count($_POST['cname']);
	for ($i=1; $i < $len; $i++)
	{

	$cname = $_POST['cname'][$i];

  $sql3 = "INSERT INTO curator SET
      cname='$cname',
      exhibitid='$exid'";
  if (@mysql_query($sql3)) {
    echo '<p>En kurator er lagt til</p>';
  } else {
    exit('<p>Feil ved innlegging av kurator: ' . mysql_error() . '</p>');
  }
	}
}

?>



<p><a href="<?php echo $_SERVER['PHP_SELF']; ?>">Legg til en ny utstilling</a></p>
<p><a href="exhibitionlist.php">Tilbake til utstillingsoversikten</a></p>

<?php
else: // Allow the user to enter a new exhibition

?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p><b>Utstillingstittel:</b><br />
<textarea name="title" rows="2" cols="60">
</textarea></p>
<p><SCRIPT LANGUAGE="JavaScript" ID="js2">
var cal2 = new CalendarPopup();
cal2.showYearNavigation();
</SCRIPT>
<b>Startdato</b><br />
<INPUT TYPE="text" name="start_date" value="" size="25">
<A HREF="#" onClick="cal2.select(document.forms[0].start_date,'anchor2','yyyy-MM-dd'); return false;" TITLE="cal2.select(document.forms[0].start_date,'anchor2','yyyy-MM-dd'); return false;" NAME="anchor2" ID="anchor2">velg</A>
</p>
<p><SCRIPT LANGUAGE="JavaScript" ID="js2">
var cal2 = new CalendarPopup();
cal2.showYearNavigation();
</SCRIPT>
<b>Sluttdato</b><br />
<INPUT TYPE="text" name="end_date" value="" size="25">
<A HREF="#" onClick="cal2.select(document.forms[0].end_date,'anchor2','yyyy-MM-dd'); return false;" TITLE="cal2.select(document.forms[0].end_date,'anchor2','yyyy-MM-dd'); return false;" NAME="anchor2" ID="anchor2">velg</A>
</p>
<div id="newlink">
<div>
<b>Kunstner:</b> 
<input type="text" name="aname[]" size="60"><br/>
<input type="hidden" name="exhibitid[]" value="<?php echo "$exid"; ?>">
</div>
</div>
<p id="addnew">
<a href="javascript:new_link()">Legg til kunstner</a>
</p>

<!-- Template -->
<div id="newlinktpl" style="display:none">
<div>
<b>Kunstner:</b> <input type="text" name="aname[]" size="60"><br/>
<input type="hidden" name="exhibitid[]" value="<?php echo "$exid"; ?>">
</div>
</div>
<div id="newlink2">
<div>
<b>Kurator:</b> 
<input type="text" name="cname[]" size="60"><br/>
<input type="hidden" name="exhibitid[]" value="<?php echo "$exid"; ?>">
</div>
</div>
<p id="addnew">
<a href="javascript:new_link2()">Legg til kurator</a>
</p>

<!-- Template -->
<div id="newlinktpl2" style="display:none">
<div>
<b>Kurator:</b> <input type="text" name="cname[]" size="60"><br/>
<input type="hidden" name="exhibitid[]" value="<?php echo "$exid"; ?>">
</div>
</div>
<input type="submit" value="LEGG TIL UTSTILLING" />
</form>
<?php endif; ?>
</body>
</html>

This is the add fields javascript:


var ct = 1;

function new_link()
{
	ct++;
	var div1 = document.createElement('div');
	div1.id = ct;

	// link to delete extended form elements
	var delLink = '<div style="text-align:right;margin-right:65px"><a href="javascript:delIt('+ ct +')">Slett</a></div>';

	div1.innerHTML = document.getElementById('newlinktpl').innerHTML + delLink;

	document.getElementById('newlink').appendChild(div1);

}
// function to delete the newly added set of elements
function delIt(eleId)
{
	d = document;

	var ele = d.getElementById(eleId);

	var parentEle = d.getElementById('newlink');

	parentEle.removeChild(ele);

}

Appriciate any help.
Thanks!

Could you at least comment your code? - Where you are inserting stuff with mysql you’re printing messages but they’re in a foreign language. In fact everything is in a foreign language which makes it a bit confusing trying to understand it and find the fault in english.

Comments are very useful.

Ok, sorry for that.
Here is the php code with comments.


<?php include 'accesscontrol.php'; ?>      
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title>Legg til en utstilling (Add exhibit)</title> 
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> 
<link href="default.css" rel="stylesheet" type="text/css" /> 
<script type="text/javascript" src="addtwofields.js"></script> 
<script type="text/javascript" src="addtwofields2.js"></script> 
<script type="text/javascript" src="CalendarPopup.js"></script> 
</head> 
<body> 
<?php 

if (isset($_POST['title'])):  


$r = mysql_query("SHOW TABLE STATUS LIKE 'exhibit' "); 
$row = mysql_fetch_array($r); 
$Auto_increment = $row['Auto_increment']; 
mysql_free_result($r); 
$exid = $Auto_increment; 


  $title = $_POST['title']; 
  $start = $_POST['start_date']; 
  $end = $_POST['end_date']; 

  $sql = "INSERT INTO exhibit SET 
      title='$title', 
      start_date='$start', 
      end_date='$end', 
      date=LOCALTIMESTAMP(), 
      galleryid='$gid'"; 
  if (@mysql_query($sql)) { 
    echo '<p>En utstilling er lagt til</p>';  //an exhibit has been added
  } else { 
    exit('<p>Error message: ' . mysql_error() . '</p>'); 
  } 

if(count($_POST)) 
{ 
    $len = count($_POST['aname']); 
    for ($i=1; $i < $len; $i++) 
    { 

  $aname = $_POST['aname'][$i]; 

  $sql2 = "INSERT INTO artist SET 
      aname='$aname', 
      exhibitid='$exid'"; 
  if (@mysql_query($sql2)) { 
    echo '<p>En kunstner er lagt til</p>'; //an artist has been added
  } else { 
    exit('<p>Error: ' . mysql_error() . '</p>'); 
  } 
    } 
} 

if(count($_POST)) 
{ 
    $len = count($_POST['cname']); 
    for ($i=1; $i < $len; $i++) 
    { 

    $cname = $_POST['cname'][$i]; 

  $sql3 = "INSERT INTO curator SET 
      cname='$cname', 
      exhibitid='$exid'"; 
  if (@mysql_query($sql3)) { 
    echo '<p>En kurator er lagt til</p>';  // a curator has been added
  } else { 
    exit('<p>Error: ' . mysql_error() . '</p>'); 
  } 
    } 
} 

?> 



<p><a href="<?php echo $_SERVER['PHP_SELF']; ?>">Legg til en ny utstilling</a></p> 
<p><a href="exhibitionlist.php">Back to exhibitlist</a></p> 

<?php 
else: // Allow the user to enter a new exhibition 

?> 

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> 
<p><b>Exhibit title:</b><br /> 
<textarea name="title" rows="2" cols="60"> 
</textarea></p> 
<p><SCRIPT LANGUAGE="JavaScript" ID="js2"> 
var cal2 = new CalendarPopup(); 
cal2.showYearNavigation(); 
</SCRIPT> 
<b>Start date</b><br /> 
<INPUT TYPE="text" name="start_date" value="" size="25"> 
<A HREF="#" onClick="cal2.select(document.forms[0].start_date,'anchor2','yyyy-MM-dd'); return false;" TITLE="cal2.select(document.forms[0].start_date,'anchor2','yyyy-MM-dd'); return false;" NAME="anchor2" ID="anchor2">velg</A> 
</p> 
<p><SCRIPT LANGUAGE="JavaScript" ID="js2"> 
var cal2 = new CalendarPopup(); 
cal2.showYearNavigation(); 
</SCRIPT> 
<b>End date</b><br /> 
<INPUT TYPE="text" name="end_date" value="" size="25"> 
<A HREF="#" onClick="cal2.select(document.forms[0].end_date,'anchor2','yyyy-MM-dd'); return false;" TITLE="cal2.select(document.forms[0].end_date,'anchor2','yyyy-MM-dd'); return false;" NAME="anchor2" ID="anchor2">velg</A> 
</p> 
<div id="newlink"> 
<div> 
<b>Artist name:</b>  
<input type="text" name="aname[]" size="60"><br/> 
<input type="hidden" name="exhibitid[]" value="<?php echo "$exid"; ?>"> 
</div> 
</div> 
<p id="addnew"> 
<a href="javascript:new_link()">Add another artist</a> 
</p> 

<!-- Template --> 
<div id="newlinktpl" style="display:none"> 
<div> 
<b>Artist name:</b> <input type="text" name="aname[]" size="60"><br/> 
<input type="hidden" name="exhibitid[]" value="<?php echo "$exid"; ?>"> 
</div> 
</div> 
<div id="newlink2"> 
<div> 
<b>Curator name:</b>  
<input type="text" name="cname[]" size="60"><br/> 
<input type="hidden" name="exhibitid[]" value="<?php echo "$exid"; ?>"> 
</div> 
</div> 
<p id="addnew"> 
<a href="javascript:new_link2()">Add another curator</a> 
</p> 

<!-- Template --> 
<div id="newlinktpl2" style="display:none"> 
<div> 
<b>Curator name:</b> <input type="text" name="cname[]" size="60"><br/> 
<input type="hidden" name="exhibitid[]" value="<?php echo "$exid"; ?>"> 
</div> 
</div> 
<input type="submit" value="Add exhibit with artist(s) and curator(s)" /> 
</form> 
<?php endif; ?> 
</body> 
</html>

The two javascripts adds another field if the exhibition has more than one artist. Same with the curator. It might be more than one.
The problem is that the form doesn’t add the first artist or curator name, just the exhibitid (hidden value) from this div. And it seems like it puts no. 2 artist where the no. 1 should have been.
I have tried several changes but had to give up, so I figured I should ask you guys.
Thanks!

What browser are you using?

I’m using Seamonkey (Firefox relative) and the add artist link works for me. The curator link doesn’t but I notice you have a seperate function for that called new_link2

EDIT: Also working in IE too.

You’re starting with the 2nd item in the array. PHP arrays are zero based. That means that the very first items index always starts at zero 0. 0 is a number just like 1,2,3 etc. Therefore it is the first number in a list of numbers.

Your code needs to look like this:


if(count($_POST))
{
	$len = count($_POST['aname']);

        //Start at 0
	for ($i=0; $i < $len; $i++)
	{

  $aname = $_POST['aname'][$i];

You should find that fixes your problem. Unfortunately because you posted so much html and javascript it was rather confusing to understand what your problem really was. I had to read it several times, copy and paste code to my server etc. I got there in the end but please try to keep things simple :wink:

Hi folks,

Thanks for helping. I’m using Safari and I tried Firefox as well - with no different result.
I changed the value to zero but then I got an extra row in the table. With no text (name), just the exhibitid ($exid). Otherwise it looks correct.
Sorry for all the html, but I feared that there was something wrong with the form itself or the javascript (it has a counter as well).

Can you do a print_r and post the results please?

Here is what I get from $sql2 (artist insert)

INSERT INTO artist SET aname=‘art1’, exhibitid='50’1
INSERT INTO artist SET aname=‘art2’, exhibitid=‘50’1
INSERT INTO artist SET aname=‘art3’, exhibitid=‘50’1
INSERT INTO artist SET aname=’’, exhibitid='50’1

I see there is someting wrong in the 4th line (I inserted 3).
Where does the ‘1’ come from behind every line? I can’t find it in the code.

When looping through an array, use foreach

I have tried with foreach but I get the same result. One empty row as earlier.


if(count($_POST))
{
	$len = count($_POST['aname']);
	for ($i=0; $i < $len; $i++)
	{
	
foreach ($_POST['aname'] as $i=>$aname) {

$sql2 = "INSERT INTO artist SET
      aname='$aname',
      exhibitid='$exid'";
	if (@mysql_query($sql2)) {
    echo '<p>En kunstner er lagt til</p>';
echo print_r($sql2);
  } else {
    exit('<p>Feil ved innlegging av kunstner: ' . mysql_error() . '</p>');
  }
	}
}
}

I’m not sure how to get the $exid add the same number of times as $aname?

Good morning,

Having had some sleep since my last reply (1am ish iirc) I’'ve had a chance to look things over with a fresh pair of eyes.

Firstly as guido says foreach is preferable but not compulsory. Admittedly I don’t use foreach much myself but do a count and a for loop like yourself.

I’ve seen a few things in your code which I’d like to get clear in my head first:


//No comments.. so what are you using auto_increment for?
$r = mysql_query("SHOW TABLE STATUS LIKE 'exhibit' "); 
$row = mysql_fetch_array($r); 
$Auto_increment = $row['Auto_increment']; 
mysql_free_result($r); 
$exid = $Auto_increment; 

The other thing I’ve noticed is that you have your template divs inside the form like this:


<form>
<!-- Template --> 
<!--THIS IS BEING SUBMITTED!-->
<div id="newlinktpl" style="display:none"> 
<div> 
<b>Artist name:</b> <input type="text" name="aname[]" size="60" value="test"><br/> 
<input type="hidden" name="exhibitid[]" value="<?php echo "$exid"; ?>"> 
</div> 
</div> 
</form>

When you submit the form they’re also being submitted adding an extra item to your loops. To prove it I added values to the text box inputs in those templates and then printed each sql statement in the loop when submitting on my local machine - Each value in the template came through with the rest of the form.

Basically when you submit your form the templates are being submitted with blank values giving you one extra item. Move the templates outside of the form and I think you’ll loose the problem. EG:


<form>
<!--Put the actual form here-->
</form>

<!--Put the templates here-->

I can’t replicate where the 1 is coming from at the end of your sql because when running your script locally it doesn’t happen to me.

Move the templates out of the form tags, give it another go and get back to me with your results.

Do a print_r of $_POST[‘aname’]. If there are empty occurrances, then you’ll have to check for that inside the loop. Only insert if there is a value to insert.

True. But since it’s preferable it might be a good idea to start using it :wink:
At least it will prevend errors like starting with 1.

Hi guys,

Thanks for helping.

Here is what that’s being printed with $_POST[‘aname’]:
Array ( [0] => k1 [1] => k2 [2] => k3 ) 1
Still the 1…
It was the form that was the problem. When I moved the templates outside the form it got right:)
(I just have to find a new way to delete a field when the user puts in one to many.)

The Auto_increment query is for pulling out the id ($exid) which will correspond for the value the new exhibit gets. Then the artist will be linked to that spesific exhibit. Is there better way?
I am also wondering how I can get a message like “x artists has been added” instead of repeating the line x times?

Just another question. Why isn’t there a [3] behind the third input in the print_r of $_POST[‘aname’]?
Array ( [0] => artist1 [1] => artist2 [2] => artist3 ) 1

Thanks!

Because arrays start counting from 0. So you have [0], [1] and [2].
That’s why foreach is so easy to use, no need to think about these things :smiley:

Because php arrays are zero based. That means it starts at zero not 1.

Yes that does seem like a rather odd issue. If you have teamviewer (fre download) I can more than happily connect to your computer and take a look at the code with you. but it will have to be in a couple of hours from now.

You could always set the templates as javascript variables.

Without seeing your database / table structure I’m still struggling to get my head around this. See auto_increment is usually a function in the mysql database - EG you can increment the id column with each new record automatically. In your case you’ve got a field named auto_increment and I’m not sure if you’re doing the same thing manually or if it serves a completely different purpose in your script and the names are coincidental? :confused:

Increment a PHP variable in each cycle of the loop and then print the above sentence with the variable in it - EG


$J = 0;
for ($I = 0; $I < $len; $I++)
   {
   //Insert here

   //Inserted? (Hint: mysql_affected_rows() )
   $J += 1;

   //Not inserted?
      //Do nothing.
   }

print "$J artists has been added";

Take a look at php’s mysql_affected_rows which you should find useful for detecting if its been inserted or not in each part of the loop.

I didn’t know about the 1 at the and of the array untill I used the print_r, and it doesn’t go into the table, so I think I can live with it. I was just curious.

Concerning the javascript: I can delete fields in the curator div so I guess I will find a way fixing it using variables.
The Auto_increment query has worked fine for a couple of other projects and it still does, so I’m happy with that for now.

I will look into the result loop later.

Thanks a lot for your help. Much appriciated:)

Glad to have helped :wink: