Jump to content

[SOLVED] Insert data but if theres a dup username just update a column?


Teck

Recommended Posts

What I'm doing is first counting the number of times unique usernames

appear in the "usernames" column, then I'm echoing it out and then later

inserting that data into another table...

 

The Problem:

When the script is run a second time, the data is reinserted, I would

prefer that it update the row if the username exists already & if not

add it in... How can i get it to do that?

 

 

$query = "SELECT username, COUNT(*) AS `col1` FROM test_table GROUP BY username ORDER BY username";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$username = $row['username'];
$col1 = $row['col1'];

echo "$username | $occurs <br>"

$query2 = "INSERT INTO a_test (username, col1) VALUES ('$username', $col1)";
$result2 = mysql_query($query2) or die('Query failed: ' . mysql_error());
}

 

 

Heres an overview of what the table looks like in case it helps

------------------------------------------------

| table: "a_test"                                          |

----------------------------------------------------

| username    | col1    | col2    | col3    | col4    |

----------------------------------------------------

| Aquila          | 42      | 521      | 46321    | 323    |

| Addison      | 35      | 854      | 15145    | 856      |

| Gareth      | 25      | 321      | 87618    | 516      |

| Finn        | 34      | 651      | 81641    | 261      |

| Jesse        | 76      | 452      | 84361    | 369    |

| Bradley    | 39      | 672      | 81651    | 814      |

| Victor      | 65      | 541      | 68932    | 675      |

| Cain        | 20      | 111      | 81118    | 548      |

---------------------------------------------------

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.