Jump to content

another newbie question


Lister471

Recommended Posts

After looking around the net and getting i feel close i though i would post and ask you all.

 

I am trying to add x number of names to a database each on its own row. I found some code and have edited it and i understand most of what its doing but i cannot get it to work, it just add witch ever name was last.

 

Here is the form code just with 3 test fields.

<form id="form1" name="form1" method="post" action="addplayer2.php">

      <p>

        <input name="player[]" type="text" id="player[]" size="15" />

      </p>

        <p>

        <input name="player[]" type="text" id="player[]" size="15" />

      </p>

        <p>

        <input name="player[]" type="text" id="player[]" size="15" />

      </p>

<input type="submit" name="submit" id="submit" value="Submit" />

</form>

 

Ok this the script i found in it unedited state, i thought i would be easy to understand if you saw it before i broke it.

 

I tried changing the word Activity to player and the work Act to play and then changing all other referanced.

<?php

$con = mysql_connect("localhost","Application","*******");

if (!$con)

{

die('Could not connect: ' . mysql_error());

}

 

mysql_select_db("CpaApp", $con);

 

foreach($_POST['Activity'] as $row=>$Act)

{

$Activity=$Act; // why does this not have post? Or is it using the one above?

$Position=$_POST['Position'][$row];

$StartDate=$_POST['StartDate'][$row];

$EndDate=$_POST['EndDate'][$row];

}

 

 

//enter rows into database

foreach($_POST['Activity'] as $row=>$Act)

{

$Activity=mysql_real_escape_string($Act); // Same question why no $_POST? does it use the one above?

$Position=mysql_real_escape_string($_POST['Position'][$row]);

$StartDate=mysql_real_escape_string($_POST['StartDate'][$row]);

$EndDate=mysql_real_escape_string($_POST['EndDate'][$row]);

}

 

 

$involv = "INSERT INTO Involvement (Activity, Position, StartDate, EndDate)

VALUES ('.$Activity.','.$Position.','.$StartDate.','.$EndDate.')";

 

 

if (!mysql_query($involv,$con))

{

die('Error: ' . mysql_error());

}

echo "$row record added";

 

mysql_close($con)

?>

 

On filling out the fields with name lets say Paul Bill and Jack it echos that it has added x number of rows but when looking in the database it has only added the last in this case Jack.

 

If there is anyone willing to edit the code above so it will work with my single field i would be very great full, also if someone would answer the questions i placed in the script that would be great also.

 

Many thanks.

Lister471

 

Link to comment
Share on other sites

You need to move the insert inside the for each loop.  this is basicly running through the array, and overwriting the values of the variables each time untill the last entry.  It's not doing anything with the variables each time round, the insert is only being called after the array has been fully run through, thus only inserting 1 record to the database.

Link to comment
Share on other sites

Yes i understand what you mean, with it not been in the loop it only adds the last name has that is the one stored rather than looping though the who list. Many thanks for that.

 

However i have move the } to include the query in the loop but it still only add 1 entry, any ideas?

Link to comment
Share on other sites

i have tried many combinations i believe the problem is with the foreach's but like i said i have tried many combinations.

 

 

<?php

include ("cone.php");

 

foreach($_POST['player'] as $row=>$play)

{

$player=$play;

}

 

foreach($_POST['player'] as $row=>$play)

{

$player=mysql_real_escape_string($play);

 

$involv = "INSERT INTO members (player)

VALUES ('.$play.')";

 

}

if (!mysql_query($involv))

{

die('Error: ' . mysql_error());

}

echo "$row record added";

 

mysql_close($con)

 

?>

Also i have tried

<?php

include ("cone.php");

 

foreach($_POST['player'] as $row=>$play)

{

$player=$play;

$player=$_POST['player'][$player];

}

 

foreach($_POST['player'] as $row=>$play)

{

$player=mysql_real_escape_string($play);

$player=mysql_real_escape_string($_POST['player'][$row]);

 

$involv = "INSERT INTO members (player)

VALUES ('.$play.')";

 

}

if (!mysql_query($involv))

{

die('Error: ' . mysql_error());

}

echo "$row record added";

 

mysql_close($con)

 

?>

 

Many thanks

Lister471

Link to comment
Share on other sites

The problem is you're not including the insert statement in your foreach loop. Try the following code:

<?php
foreach($_POST['player'] as $row => $play)
{
$player = mysql_real_escape_string($play);
$query = "INSERT INTO `members` (`player`) VALUES ('$player')";
if(!mysql_query($query))
{
	die('Error: ' . mysql_error . '<br />Query: ' . $query); //NOTE: Never use a die statement like this outside of a development environment. It gives to much information away to potential hackers.
}
else
{
	echo "$row record added<br />";
}
}
mysql_close($con)
?>

Link to comment
Share on other sites

Many thanks, i understand now you have shown me what was meant about including it in the loop. Many thanks for your help.

 

I have tested and it works just fine now with your code so again thanks. I do have 1 more question though.

 

In the form there will be 32 fields has we are hoping for 32 signups, however on testing i noticed that it added a blank entry for the fields left blank. Is there anyway to stop this and only had entry's for fields with data?

 

Thanks again. It was very kind of you to help.

 

Lister471

Link to comment
Share on other sites

No problems :). Always happy to help people learn PHP. To skip over blank cells change the code here:

$player = mysql_real_escape_string($play);
$query = "INSERT INTO `members` (`player`) VALUES ('$player')";

to:

if(!$play)
{
continue;
}
$player = mysql_real_escape_string($play);
$query = "INSERT INTO `members` (`player`) VALUES ('$player')";

Link to comment
Share on other sites

Please don't run queries in loops unless it's absolutely necessary (it usually isn't). Since the inputs are all strings from text type form fields, they should be: trim()med, checked and removed if empty(), and escaped. Then you can implode them into a string, and run one query to insert them all at once. If this is something you do in more than one script, you can wrap everything in a function and use it in other places as well. This function will work multiple record inserts in a single db field, but you could modify it to do more.

 

// make sure db connection has been established before calling the function . . .
function INSERT_ARRAY_VALUES( $array ) {
   if( !is_array($array) ) {
      exit('Function INSERT_ARRAY_VALUES() requires an array.');
   }
   $array = array_map('trim', $array);
   $array = array_map('mysql_real_escape_string', $array);
   foreach( $array as $k => $v ) {
      if( is_array($v) ) {
         exit('Function INSERT_ARRAY_VALUES() is not recursive');
      } else {
         if( empty($v) ) {
            unset( $array[$k] );
         }
      }
   }
   $string = implode( "' ), ( '", $array );
   return($string);
}
$array = array('', '', "Sally's ball", 'Joey', 'Small sentence.');
$string = INSERT_ARRAY_VALUES($array);

// USAGE

$query = "INSERT INTO table ( field ) VALUES ( '$string' )"; 

echo $query; 
//returns: INSERT INTO table ( field ) VALUES ( 'Sally\'s ball' ), ( 'Joey' ), ( 'Small sentence.' )

Link to comment
Share on other sites

I was just asking to see if there was another answer other than the overhead. For most scripts I get the point, for a small script like this I find it's just easier to put it in the loop, especially for new programmers as I think my example is a lot easier to understand what is going on that yours, no offence.

Link to comment
Share on other sites

Another question.

 

I need to make the code that inserts the data also insert the number for the team. So player 1 and player 2 will show has team 1 player 3 and player 4 has team 2. The changes i have made work but it simply add's the first number 1 and then keeps adding 1 to it. So player 1 is on team 1 player 2 is on team 2 and so.

 

Is there away to make it so it inserts 2 numbers at time, i dont know how to explain it i cannot get it out of my head onto screen so it makes sence. I hope you get what i mean.

 

Here is the code from above with a simple edit.

<?php

include ("cone.php");

$i = 0;

foreach($_POST['player1'] as $row => $play1)

{

++$i;

$player1 = mysql_real_escape_string($play1);

$query = "INSERT INTO `teams` (`mname`,`teamn`) VALUES ('$player1', '$i')";

if(!mysql_query($query))

{

echo "error";

}

else

{

echo "Teams are set<br />$player1 and $i";

}

}

?>

Link to comment
Share on other sites

So, for each 2 entries, the team number should increment then? That can also be done in a single query, like so:

 

<?php
include ("cone.php");
$i = 0;
$t = 1;
foreach($_POST['player1'] as $v) {
if( $i % 2 === 0 && $i !== 0 ) {
	$t++;
}
$player1 = mysql_real_escape_string($v);
$array[] = "( '$v', $t )";
$i++;
}

$string = implode( ', ', $array );

$query = "INSERT INTO `teams` (`mname`,`teamn`) VALUES $string";
echo $query;
if(!mysql_query($query)) {
echo "error";
} else {
echo "Query executed successfully, and inserted " . mysql_affected_rows() . "records.";
}

Link to comment
Share on other sites

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.