Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

I have an array $playernames which holds different player names. Im trying to extract the values and upload them to a database one query per time, as such:

for ($i=0; sizeof($playername) > $i; $i++)
{
    $name = $playername[$i];
    $query = mysql_query(
        "INSERT INTO `team`(`fixture_id`,`player_name`
    ) 
    VALUES ($id, '$name')") or die(mysql_error());  
}

However what now happens now is after every query in the loop the data gets overwrited in the name colum of database. After execution when I open the DB only the name of the last player contained in the array is displayed.

What am I doing wrong? Thanks in advance. (sorry if this question touches on duplicate but I've not seen a clear explanation regarding above problem)

share|improve this question
    
you can alter your table and make the fixture_id to auto-increment , so u will care about sending it to the DB anymore .. mysql will handle it for you. – Leo Bali Oct 3 '13 at 7:33

3 Answers 3

up vote 3 down vote accepted

You are not initializing/changing the value of the variable $id for fixture_id.

Hence, it is taking the default value.

If your fixture_id is set to AUTO INCREMENT, modify your query as:

 $query = mysql_query("INSERT INTO `team`(`player_name`) 
    VALUES ('$name')") or die(mysql_error());  

And fixture_id will take automatically incremented value.

Or set $id from the array $playername.

Also, modify the statement:

for ($i=0; sizeof($playername) > $i; $i++)

To:

$len = sizeof($playername);
for ($i=0; $len > $i; $i++)

As you are calling a PHP function too many times (equal to the array length), this may be a performance hit.

By doing this, we are using a variable $len instead of many function calls.

Hope this works for you.

share|improve this answer

The fixture_id in your SQL, provided by the variable $id never changes. Hence, each query is overwriting the values of the previous one. You probably need to add some logic to change $id in each loop iteration as well.

share|improve this answer

It seems that $id value is not set or is the same all the time, you probably wanted to use $i instead like:

for ($i=0; sizeof($playername) > $i; $i++)
{
    $name = $playername[$i];
    $query = mysql_query("INSERT INTO `team`(`fixture_id`,`player_name`) 
    VALUES ($i, '$name')") or die(mysql_error());  
}

Also you can create auto-increment column and then just insert it like this:

foreach($playername as $name){

    $query = mysql_query("INSERT INTO `team`(`fixture_id`,`player_name`) 
            VALUES ('', '$name')") or die(mysql_error());
}

where fixture_id is automatically incremented in mysql

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.