Duplicate entry '' for key 1 mysql error

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
PHP_Ste
Forum Newbie
Posts: 19
Joined: Thu Mar 10, 2005 8:42 am

Duplicate entry '' for key 1 mysql error

Post by PHP_Ste »

Can anyone please tell me what this error usually means? One of my queries has it. What checks should I do to fix it?
thegreatone2176
Forum Contributor
Posts: 102
Joined: Sun Jul 11, 2004 1:27 pm

Post by thegreatone2176 »

it means your field is set as unique and you are inserting something that is already in there

to check for it for something like usernames on a site you could do

Code: Select all

$check = "SELECT * FROM users WHERE username='$username'";
$res = mysql_query($check):
$total = mysql_num_rows($res);

if ($total > 0){
echo "Username already taken";
die;
}
PHP_Ste
Forum Newbie
Posts: 19
Joined: Thu Mar 10, 2005 8:42 am

Post by PHP_Ste »

Thanks.
PHP_Ste
Forum Newbie
Posts: 19
Joined: Thu Mar 10, 2005 8:42 am

Post by PHP_Ste »

Right I know what the problem is I just don't know how to fix it. On one page I ask the user how many members are in their band and how many bands influence them, I do 2 loops to generate the amount of forms needed then I do two loops to insert the data from the forms into the database.

The problem is it's doing the insert loops before the user has chance to enter anything so they're entering " " into each field in the database. So say I put 3 in each edit box it generates the edit boxes needed for 3 band members and influences and then is inserting " " into each field, seen as the primary key fields are unique this is where the problem is.

So in a nutshell I need to get the form to post as it should and then the problem will be fixed.

I've tried using if(isset($_POST)) { and if(!empty($_POST)) but no joy.

The code for bands.php is below, this is the page that asks for the number of edit boxes:

Code: Select all

<?php 
session_start(); 
?> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<title>Welcome to DIYMusic.com</title> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
</head> 

<body bgcolor="#000000" text="#CCCCCC" link="#666666" vlink="#666666"> 
<?php if(isset($_SESSION['valid_user'])) { ?> 
<table width="89%" height="462" border="0"> 
<tr> 
<tr><td width="40%" height="305" valign="top"><img src="Register%20Side%20Bar.jpg" width="290" height="500" border="0" usemap="#Map"></td> 

<td width="60%" valign="top"><p>Hello <? echo $_SESSION['valid_user']; ?>, welcome to the backstage area! <a href="logout.php">LOG OUT</a></p> 

<p></p> 
<p></p> 
<p></p>
<p></p> 
<p></p> 
      <table width="100%" border="0">
        <tr> 
          <form method="post" action="submit.php">
          <td width="26%"><p>How Many Band Members are there in your Band?</p>
            <p></p></td>
          <td width="66%"> 
	<input type="text" name="member" style="width: 20px">
            </p>
          <td width="2%">
          <td width="6%">&nbsp; 
          <tr> 
            <td width="26%"><p>How Many Bands have Directly Influenced Your Band?</p></td>
              <td><input type="text" name="influences" style="width: 20px">
                </td>
            
          <tr> 
            <td></td>
          </tr>
          <tr> 
            <td><p> 
                <input type="submit" name="Submit" value="Submit Details">
              </p></td>
          </tr>
      </table>



</td> 
</tr> 
</form>
</table> 

<?php

 
?>

<map name="Map"> 
<area shape="rect" coords="97,138,198,172" href="index.htm" alt="Go Back to Welcome Page"> 
<area shape="rect" coords="95,180,196,213" href="login.php" alt="Go Back to Login"> 

</map> 
<? 
session_destroy(); 
} 
else 
{ 
session_destroy(); 

echo'You have to have registered and logged in to view this page, register <a href="Register.php">here</a>'; 

} 

?> 

</body> 
</html>
The code for submit.php is below, this is the page where the problem is.

Code: Select all

<?php 
session_start(); 
include('connect.inc');
?> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<title>Welcome to DIYMusic.com</title> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
</head> 

<body bgcolor="#000000" text="#CCCCCC" link="#666666" vlink="#666666">
<table width="96%" height="1000" border="0">
  <tr>
    <td width="31%" valign="top"><img src="Register%20Side%20Bar.jpg" width="290" height="500" border="0" usemap="#Map"></td>

<div align="center"><b>Enter the details of each member of your band and each band who has influenced you below:</b></div>

<p></p>
<p><p>
<p></p>

<td width="69%" valign="top"><form action="fileupload.php" method="post">

<b><i>Members:</i></b>

<?php
$i=1;

$loginname = $_SESSION['valid_user'];
$_SESSION['no_of_influences'] = $HTTP_POST_VARS['member']; 
$_SESSION['no_of_members'] =  $HTTP_POST_VARS['influences'];
while ($i <=  $_SESSION['no_of_members'])
{
?>

<table border="0">
<tr><td><p>
<strong>Member</strong></td>
<td><input type="text" name=<?"'member ' . $i . '"?>  style="width: 175px">
</td></tr>

<tr><td>
<strong>Role</strong></td>
<td><input type="text" name=<?"'role ' . $i . '"?> style="width: 175px">
</td></tr>

<tr><td>
<strong>Description</strong></td>
<td><input type="text" name= <?"'mdescription ' . $i . '"?> style="width: 175px">
</td></tr>

<?php

$i++;
}

?>
<tr><td><b><i>Influences:</i></b></td></tr>

<?php

$n=1;

while ($n <=  $_SESSION['no_of_influences'])
{
echo'<p><tr><td>
<strong>Influence</strong></td>
<td><input type="text" name="influence ' . $n . '" style="width: 175px">
</td></tr>';

echo'<tr><td>
<strong>Description</strong></td>
<td><input type="text" name="description ' . $n . '" style="width: 175px">
</td></tr>';

$n++;
}

if(isset($_POST)) {

$sql = "SELECT band_ID FROM user where login_name = '$loginname'";
$result = mysql_query($sql);
$bandID = mysql_fetch_array($result);

$i=1;

while ($i <=  $_SESSION['no_of_members']) 
{
$member = $_POST['member ' . $i . ''];
$role= $_POST['role ' . $i . ''];
$mdescription= $_POST['mdescription ' . $i . ''];

$sql = "INSERT INTO `member` (`band_ID`, `member_name`) 
VALUES (
'$bandID', '$member'
)";

mysql_query($sql, $dbh) or die("Failed <pre>$sql</pre>".mysql_error());

$memberID = mysql_insert_ID();

$sql = "INSERT INTO `member_role` (`member_ID`, `role`) 
VALUES(

'$memberID', '$role'

)";

mysql_query($sql, $dbh) or die("Failed <pre>$sql</pre>".mysql_error());

$sql = "INSERT INTO `role` (`role`, `description`) 
VALUES(

'$role', '$description'

)";

mysql_query($sql, $dbh) or die("Failed <pre>$sql</pre>".mysql_error());

$i++;

}

$n=1;

while ($n <=  $_SESSION['no_of_influences']) 
{ 
$influence = $_POST['influence ' . $n . ''];
$description= $_POST['description ' . $n . ''];

$sql = "INSERT INTO `bandinfluence` (`band_ID`, `influence`) 
VALUES(

'$bandID', '$influence';

)";

mysql_query($sql, $dbh) or die("Failed <pre>$sql</pre>".mysql_error());

$sql = "INSERT INTO `influence` (`influence`, `description`) 
VALUES(

'$influence', '$description'

)";

mysql_query($sql, $dbh) or die("Failed <pre>$sql</pre>".mysql_error());

$n++;

}

echo'Your Members and Influences are now in the database, all you need to do now is upload your mp3!';

}

?>

<tr></tr>
<tr><td></td>
<td><input type="submit" name="submit" value="Submit Details" /></td></tr>

</table>
</form>
</table>
</body> 
</html>
User avatar
infolock
DevNet Resident
Posts: 1708
Joined: Wed Sep 25, 2002 7:47 pm

Post by infolock »

just as soon as i saw this i stopped reading the rest of your code...

this line :
if(isset($_POST))

is incomplete. you need to specify what POST data that the if statement is suposed to be looking at...
(ie $_POST['text_box_name_here'] )
PHP_Ste
Forum Newbie
Posts: 19
Joined: Thu Mar 10, 2005 8:42 am

Post by PHP_Ste »

Thanks for the help.

Can I specify multiple text boxes within them brackets?
User avatar
infolock
DevNet Resident
Posts: 1708
Joined: Wed Sep 25, 2002 7:47 pm

Post by infolock »

no (well..maybe, but that's beyond my own comprehension), but you could join other post's together in 1 if

example :

Code: Select all

if(isset($_POST['text1']) && isset($_POST['text2']) && isset($_POST['text3']))
{
     //then do something
}
Last edited by infolock on Sat Mar 12, 2005 7:22 am, edited 1 time in total.
PHP_Ste
Forum Newbie
Posts: 19
Joined: Thu Mar 10, 2005 8:42 am

Post by PHP_Ste »

Thanks alot. :)
User avatar
infolock
DevNet Resident
Posts: 1708
Joined: Wed Sep 25, 2002 7:47 pm

Post by infolock »

np at all 8)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

isset() will only really help you detect if the page request is a post versus get with the code above.. If that's all you want to check

Code: Select all

if(strcasecmp($_SERVER['QUERY_METHOD'],'post') == 0)
{
  // it's a post
}
else
{
  // it isn't a post
}
PHP_Ste
Forum Newbie
Posts: 19
Joined: Thu Mar 10, 2005 8:42 am

Post by PHP_Ste »

Now nothing's happening when I submit the form. Well when I say nothing I mean my edit boxes are dissapearing and no data is going into the database, when before it was submitting data as the page loaded so I know my queries are working, the only thing I've changed is added another two if statements and modified the isset if statement:

I checked the names of the text boxes and they match up unless me eye sights going.

Code: Select all

if(isset($_POST&#1111;'member ' . $i . '']) &amp;&amp; isset($_POST&#1111;'role ' . $i . '']) &amp;&amp; 
isset($_POST&#1111;'mdescription ' . $i . '']) &amp;&amp; isset($_POST&#1111;'influence ' . $n . '']) &amp;&amp;
($_POST&#1111;'description ' . $n . ''])) {
If there is a role and description entered that are not stored in the database then insert them into the role table.

Code: Select all

$sql = "SELECT * FROM role WHERE role == $role && description == $mdescription";
$result = mysql_query($sql) or die("Failed <pre>$sql</pre>".mysql_error());

 if (mysql_num_rows($result) == 0 ) {


$sql = "INSERT INTO `role` (`role`, `description`) 
VALUES(

'$role', '$description'

)";

mysql_query($sql, $dbh) or die("Failed <pre>$sql</pre>".mysql_error());

$i++;

}

}
If there's an influence and description not already stored in the database then insert them into the the influence table.

Code: Select all

$sql = "SELECT * FROM influence WHERE influence == $influence && description == $description";
$result = mysql_query($sql) or die("Failed <pre>$sql</pre>".mysql_error());

 if (mysql_num_rows($result) == 0 ) {

$sql = "INSERT INTO `influence` (`influence`, `description`) 
VALUES(

'$influence', '$description'

)";

mysql_query($sql, $dbh) or die("Failed <pre>$sql</pre>".mysql_error());

$n++;
}

feyd | Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]
PHP_Ste
Forum Newbie
Posts: 19
Joined: Thu Mar 10, 2005 8:42 am

Post by PHP_Ste »

feyd wrote:isset() will only really help you detect if the page request is a post versus get with the code above.. If that's all you want to check

Code: Select all

if(strcasecmp($_SERVER['QUERY_METHOD'],'post') == 0)
{
  // it's a post
}
else
{
  // it isn't a post
}
Tried that, still doesn't work.
feyd | Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read:  Posting Code in the Forums[/quote]

OK will do in future.
User avatar
infolock
DevNet Resident
Posts: 1708
Joined: Wed Sep 25, 2002 7:47 pm

Post by infolock »

you are doing your sql statements in a very odd way. the manual itself for mysql doesn't even list == has a valid operator heh..

http://dev.mysql.com/doc/mysql/en/functions.html

I have went through your code thoroughly and you have a lot of serious mistakes and problems in it... I've pointed out a lot of them... and there are others as well.

so anyways, this

Code: Select all

$sql = "SELECT * FROM role WHERE role == $role && description == $mdescription";
should be this

Code: Select all

$sql = "SELECT * FROM role WHERE role = '".$role."' AND description = '".$mdescription."'";

and this

Code: Select all

$sql = "SELECT * FROM influence WHERE influence == $influence && description == $description";
should be

Code: Select all

$sql = "SELECT * FROM influence WHERE influence = '".$influence."' AND description = '".$description."'";


ALso, you are using Obsolete $HTTP_POST_VARS.

Code: Select all

$_SESSION['no_of_influences'] = $HTTP_POST_VARS['member']; $_SESSION['no_of_members'] =  $HTTP_POST_VARS['influences'];
You should instead be using $_POST....

Code: Select all

$_SESSION['no_of_influences'] = $_POST['member']; $_SESSION['no_of_members'] =  $_POST['influences'];


shouldn't this :

Code: Select all

$_SESSION['no_of_influences'] = $_POST['member'];
$_SESSION['no_of_members'] =  $_POST['influences'];
be this??

Code: Select all

$_SESSION['no_of_influences'] = $_POST['influences'];
$_SESSION['no_of_members'] =  $_POST['member'];


Last but not least, I don't (by any means) understand the point of this IF statement :

Code: Select all

if(isset($_POST['member ' . $i . '']) && isset($_POST['role ' . $i . '']) && isset($_POST['mdescription ' . $i . '']) && isset($_POST['influence ' . $n . '']) &&($_POST['description ' . $n . ''])) {
you are trying to check the $_POST data on values that aren't getting submitted to THIS scrip, but data that's getting posted to ANOTHER script. Thus, this if will NEVER ring true...which is why it doesn't work now for you... before, it was just saying "if there is a post, then do this". well, yeah, there probably would be a post, but is it the post that you wanted to make sure they had set? if you are just wanting something to let you do something after that if statement, why not just omit the IF statement all together and just run what you were wanting to do??


I just think you need to do a little more studying and referencing to the php manual and then tackle this again. your concept of how this works is very strong, i just think you are throwing things together, hoping it works, and when it doesn't just give up.

if you have any other questions, feel free to ask =)
Post Reply