I am trying to upload two sets of multiple selects into a MariaDB database (many to many relationship intermediate table). The selected options are being properly uploaded but the code is also sending in the last entry from both selects. In other words, if I select options 1 and 4 from the first select that contains 10 options, and I select 5 and 12 from the second select that contains 15 options, instead of populating 4 entries (1 and 5, 1 and 12, 4 and 5, 4 and 12) it is populating 9 options (the four that are supposed to be there plus 1 and 15, 4 and 15, 10 and 15, etc). Each select is populated from the two tables. Below is the code.
<?php
include ("connect_movieDB.php");
connectDB();
$display_block = "<h1>Populate Movie-Actor table</h1></br>
<p>Select a movie and select the actors</p>";
$get_movie_sql = "SELECT id as movie_id, movie_title, movie_releasedate FROM movies ORDER BY movie_title asc";
$get_movie_results = mysqli_query($mysqli, $get_movie_sql) or die(mysqli_error($mysqli));
$get_actor_sql = "SELECT id as actor_id, CONCAT_WS(' ', f_name, l_name) AS display_name FROM actors ORDER BY l_name asc, f_name asc";
$get_actor_results = mysqli_query($mysqli, $get_actor_sql) or die(mysqli_error($mysqli));
if ((mysqli_num_rows($get_movie_results) < 1) || (mysqli_num_rows($get_actor_results) < 1)) {
$display_block .= "<p><em>Did we forget to populate the database?</em></p>";
} else {
$display_block .= "
<form method=\"post\" action=\"".$_SERVER['PHP_SELF']."\">
<p><label for=\"sel_movie\">Select a movie:</label></br>
<select id=\"sel_movie\" size=\"10\" name=\"sel_movie[]\" required=\"required\" multiple=\"multiple\">
<option value=\"\">--Select a Movie--</option>";
while ($movies = mysqli_fetch_array($get_movie_results)) {
$movieid = $movies['movie_id'];
$display_movie_title = stripslashes($movies['movie_title']);
$display_moviedate = stripslashes($movies['movie_releasedate']);
$display_block .="<option value=\"".$movieid."\">".$display_movie_title." - (".$display_moviedate.")</option>";
}
$display_block .= "
</select></br>
<p><label for \"sel_actor\">Select the actors in the movie:</label></br>
<select id=\"sel_actor\" size=\"10\" name=\"sel_actor[]\" required=\"required\" multiple=\"multiple\">
<option value=\"\">--Select actor(s)--</option>";
while ($actors = mysqli_fetch_array($get_actor_results)) {
$actorid = $actors['actor_id'];
$display_actor_name = stripslashes($actors['display_name']);
$display_block .="<option value=\"".$actorid."\">".$display_actor_name."</option>";
}
$display_block .="
</select></p>
<input type=\"hidden\" name=\"sel_movie[]\" value='".$movieid."'/>
<input type=\"hidden\" name=\"sel_actor[]\" value='".$actorid."'/>
<button = type=\"submit\" name=\"submit\" value=\"addtotable\">Add Relationship</button>
<p>Return to the main menu</p>
</form>";
}
if ($_POST) {
if ((isset($_POST['sel_movie'])=="") || (isset($_POST['sel_actor'])=="")){
header("location: addto_ma_table.php");
exit;
}
connectDB();
$movie_array = $_POST['sel_movie'];
$actor_array = $_POST['sel_actor'];
foreach($movie_array as $m) {
foreach($actor_array as $a) {
$check_sql = "SELECT movie_id, actor_id FROM movie_actor WHERE movie_id ='".$m."' AND actor_id ='".$a."'";
$check_results = mysqli_query($mysqli, $check_sql) or die(mysqli_error($mysqli));
$add_info_sql = "INSERT INTO movie_actor (movie_id, actor_id) VALUES ('".$m."', '".$a."')";
$add_info_results = mysqli_query($mysqli, $add_info_sql) or die(mysqli_error($mysqli));
header("Location: addto_ma_table.php");
}
} mysqli_close($mysqli);
}
?>
Thanks for any assistance
There are two hidden inputs after you close the second select. They are adding the last values from your queries to the post arrays. Remove those and it should work better.
Related
first sorry for my english. I have a problem on my isset Here's the codes:
PHP:
if(isset($_POST['insert'])) {
$insert = $_POST['insert'];
}
{
require('./clanconfig.php');
$cln = $_POST['clanname'];
$cms = $_POST['mesa'];
$checkup = "SELECT id FROM clan WHERE cname='$cln'";
$upsql = mysqli_query($conn, $checkup);
while($srcclan=mysqli_fetch_array($upsql) )
{
$checked = $srcclan['id'];
}
$sql2 = "INSERT INTO clanrequest (clanid, plname, message, playerid) VALUES('$cln', '$uname', '$cms', '$player_id')";
$sql3 = mysqli_query($conn, $sql2) or die();
}
mysqli_close($conn);
Problem is While searching on table1 with a Post value it's okay but while inserting on table 2 with a id of table 1 and on table 2 adding but value is only 0 on id column
Html:
<form class="clan-form-join action="clanjoin.php" method="post">
<?php
require('./clanconfig.php');
$sql = "SELECT * FROM clan";
$sql2 = mysqli_query($conn, $sql);
echo "<html>";
echo "<body>";
echo "<select name='clanname'>";
while($sonuct=mysqli_fetch_array($sql2) )
{
$cnamer = $sonuct['cname'];
echo '<option value=" '.$cnamer.'">'.$cnamer.'</option><br />';
}
echo "</select>";
echo "</body>";
echo "</html><br>";
echo'<b>Message</b><br><textarea name="mesa" rows=3 cols=40></textarea><br/>';
echo'<input type="submit" name="insert" class="clanbutton" value=" Send Application ">';
?>
</form>
Here's the html codes, i select the details of clan in a clan table and when member select the clan name and insert the button the codes sent with a clan name selected like test clan in isset value and in the isset select the id of clan selected on option value clan name on table clan and return to insert clan request with name,id of player and where id of clan the problem is id of clan adding automatically 0 without add real id of clan
All the code for inserting should be inside the if (isset($_POST['insert'])). You only have the variable assignment there (and you never even use that variable), you have the rest of the code in a separate block (there's no purpose to putting it in a block).
if(isset($_POST['insert'])) {
$insert = $_POST['insert'];
require('./clanconfig.php');
$cln = $_POST['clanname'];
$cms = $_POST['mesa'];
$checkup = "SELECT id FROM clan WHERE cname='$cln'";
$upsql = mysqli_query($conn, $checkup);
while($srcclan=mysqli_fetch_array($upsql) )
{
$checked = $srcclan['id'];
}
$sql2 = "INSERT INTO clanrequest (clanid, plname, message, playerid) VALUES('$cln', '$uname', '$cms', '$player_id')";
$sql3 = mysqli_query($conn, $sql2) or die();
mysqli_close($conn);
}
I'm working on a Tabletop RPG Monster Database for a class, and I need to insert values into my Monster Table with these parameters: Monster Table.
CREATE TABLE Monsters (
ID int NOT NULL AUTO_INCREMENT,
Name varchar(100) NOT NULL,
HP int unsigned NOT NULL,
MP int unsigned NOT NULL,
AC int unsigned NOT NULL,
MonsterType_ID int NOT NULL,
PRIMARY KEY(ID),
FOREIGN KEY(MonsterType_ID) REFERENCES MonsterType(ID) ON DELETE CASCADE
) ENGINE=InnoDB;
I also have a MonsterType Table
CREATE TABLE MonsterType (
ID int NOT NULL AUTO_INCREMENT,
Name varchar(100) NOT NULL,
PRIMARY KEY (ID)
) ENGINE=InnoDB;
I have PHP code set up: PHP Monster Query
if (isset($_POST["submit"])) {
if( (isset($_POST["Name"]) && $_POST["Name"] !== "") &&
(isset($_POST["HP"]) && $_POST["HP"] !== "") &&
(isset($_POST["MP"]) && $_POST["MP"] !== "") &&
(isset($_POST["AC"]) && $_POST["AC"] !== "") &&
(isset($_POST["MonsterType_ID"]) && $_POST["MonsterType_ID"] !== "") ) {
$query = "INSERT INTO Monsters ";
$query .= "(Name, HP, MP, AC, MonsterType_ID) ";
$query .= "VALUES (";
$query .= "'".$_POST["Name"]."',";
$query .= "'".$_POST["HP"]."',";
$query .= "'".$_POST["MP"]."',";
$query .= "'".$_POST["AC"]."',";
$query .= "'".$_POST["MonsterType_ID"]."');";
$result = $mysqli->query($query);
When I go to Add Monsters, the Monster Type field only accepts integer values corresponding to the MonsterType.ID index. Instead, I'd like to be able to, in the text field, type out the MonsterType Names
INSERT INTO MonsterType (Name)
VALUES
('Abberation'),
('Beast'),
('Celestial'),
('Construct'),
('Dragon'),
('Elemental'),
('Fey'),
('Fiend'),
('Giant'),
('Humanoid'),
('Monstrosity'),
('Ooze'),
('Plant'),
('Undead');
and have the corresponding Type Name's ID inserted into the database.
I can already display the MonsterType associated with the Monster using this query: Monster Display
$query = "SELECT Monsters.ID AS `mID`,
Monsters.Name AS `MName`, Monsters.MonsterType_ID,
MonsterType.Name FROM Monsters ";
$query .= "inner join MonsterType ON Monsters.MonsterType_ID = MonsterType.ID
ORDER BY MonsterType.Name ASC";
$result = $mysqli->query($query);
if ($result && $result->num_rows > 0) {
echo "<div class='row'>";
echo "<center>";
echo "<h2>The Monster Database</h2>";
echo "<table>";
echo "<tr><th>Name</th><th>Type</th>
<th></th><th></th></tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr>";
//Output FirstName and LastName
echo "<td>" .$row["MName"]."</td>";
echo "<td>" .$row["Name"]."</td>";
I'm just not sure how to go about changing my Insert query such that it will accept the MonsterType.Name in the text field and use the MonsterType.ID associated with that MonsterType.Name in my Insert into Monsters table query.
Of course, ideally I'd just want my Monster Type field to be a dropdown list of all the MonsterType.Names but I was having issues doing a dropdown field using HTML code embedded in a PHP block.
echo '
<div class="row">
<label for="left-label" class="left inline">
<h2>Add a monster</h2>
<form method="POST" action="addMonsters.php">
<p> Monster Name: <input type="text" name="Name">
<p> Hit Points: <input type="text" name="HP">
<p> Mana Points: <input type="text" name="MP">
<p> Armor Class: <input type="text" name="AC">
<p> Monster Type: <input type="text" name="MonsterType_ID">
/////// This didn't work
<p>Monster Type: <select name="Name">
<option></option>
<?php
$query = "SELECT DISTINCT Name FROM MonsterType";
$result = $mysqli->query($query);
if($result && $result->num_rows>=1){
while($row = $result->fetch_assoc()){
echo "<option value = '".$row['Name']."'>".$row['Name']."/option>";
}
}
else {echo "<h2>No query results</h2>";}
?>
</select>
///////////
<input type="submit" name="submit" class="button tiny round" value="Add monster" />
</form>
';
If someone could solve this, that would be better.
Any guidance would be appreciated! Thank you!
EDIT:
I've successfully populated my dropdown using this block of code:
echo '<p>Monster Type: <select name="MonsterType_ID">';
echo '<option></option>';
$query = "SELECT DISTINCT ID, Name FROM MonsterType";
$result = $mysqli ->query($query);
if($result && $result->num_rows>=1){
while($row2 = $result->fetch_assoc()){
if($row2['mID'] == $MonsterID){
echo "<option selected value = '".$row2['ID']."'>".$row2['Name']."</option>";
}
else{
echo "<option value = '".$row2['ID']."'>".$row2['Name']."</option>";
}
}
}
else {
echo "<h2>No query results</h2>";
}
echo '</select></p>';
However, this doesn't correctly POST to the original query, and I get the error message that I haven't filled in all the information. (I was missing a quotation marks around (select name="MonsterType_ID")) However, I'm still getting "Error! Could not add ".$_POST["Name"]."!"; So this means the result of the Query is false. Not sure what could be going on, except maybe MonsterType.ID is not getting matched to Monsters.MonsterType_ID.
if (isset($_POST["submit"])) {
if( (isset($_POST["Name"]) && $_POST["Name"] !== "") &&
(isset($_POST["HP"]) && $_POST["HP"] !== "") &&
(isset($_POST["MP"]) && $_POST["MP"] !== "") &&
(isset($_POST["AC"]) && $_POST["AC"] !== "") &&
(isset($_POST["MonsterType_ID"]) && $_POST["MonsterType_ID"] !== "") ) {
//STEP 2.
//Create query to insert information that has been posted
$query = "INSERT INTO Monsters ";
$query .= "(Name, HP, MP, AC, MonsterType_ID) ";
$query .= "VALUES (";
$query .= "'".$_POST["Name"]."',";
$query .= "'".$_POST["HP"]."',";
$query .= "'".$_POST["MP"]."',";
$query .= "'".$_POST["AC"]."',";
$query .= "'".$_POST["MonsterType_ID"]."'));";
//$query .= "(SELECT ID FROM MonsterType WHERE Name='".$_POST["MonsterType_ID"]."'));";
$result = $mysqli->query($query);
// Execute query
if($result) {
$_SESSION["message"] = $_POST["Name"]." has been added!";
header("Location: readMonsters.php");
exit;
}
else {
$_SESSION["message"] = "Error! Could not add ".$_POST["Name"]."!";
header("Location: addMonsters.php");
exit;
}
}
else {
$_SESSION["message"] = "Unable to add monster. Fill in all information!";
header("Location: addMonsters.php");
exit;
}
EDIT 2: Got everything working! The dropdown was correct, I just need to change the query to accept the proper parameter.
$query = "INSERT INTO Monsters ";
$query .= "(Name, HP, MP, AC, MonsterType_ID) ";
$query .= "VALUES (";
$query .= "'".$_POST["Name"]."',";
$query .= "'".$_POST["HP"]."',";
$query .= "'".$_POST["MP"]."',";
$query .= "'".$_POST["AC"]."',";
//$query .= "'".$_POST["MonsterType_ID"]."'));";
$query .= "(SELECT ID FROM MonsterType WHERE ID='".$_POST["MonsterType_ID"]."'));";
$result = $mysqli->query($query);
Namely, I changed (SELECT ID FROM MonsterType WHERE Name=...) to (SELECT ID FROM MonsterType WHERE ID=...). My dropdown now successfully works. Thank you Nick for your help!
Short answer, given your current code structure, change this line:
$query .= "'".$_POST["MonsterType_ID"]."');";
to
$query .= "(SELECT ID FROM MonsterType WHERE Name='".$_POST["MonsterType_ID"]."'));";
This will do a subquery select to get the appropriate ID from MonsterType for the name submitted.
Long Answer
The issue with this approach is that if a user types something into the MonsterType_ID text box that is not a valid MonsterType e.g. they mistype "Aberration" for "Abberation" this query will fail. Your attempt at generating a drop-down list is the right way to go. You will want something like this:
<p>Monster Type: <select name="MonsterType_ID">
<?php
$query = "SELECT ID, Name FROM MonsterType";
$result = $mysqli->query($query);
if ($result) {
while ($row = $result->fetch_assoc()) {
echo "<option value = \"" . $row['ID'] . "\">" . $row['Name'] . "</option>";
}
}
?>
</select>
This will give you a select where the option values (which are what gets passed to PHP in $_POST) are the ID's that you need to insert into the Monsters database. This way you don't need to do any pre-processing as described in the short answer (basically your existing code will work as is).
You can use a select when you do the insert.
INSERT INTO monsters (your, variable, fields, here, monsterTypeID)
Select 'varname', 'varname', 'varname', 'varname', monsterTypeID FROM
MonsterTypeNames WHERE name='namevar';
You will want to query the monstertype table to get the id based on the monstertype name, and use the retrieved monstertype id to form part of your insert query.
So the solutions are that you either split it into two queries or use insert select(insert with subquery). If you split it into two queries, you will have to select, then insert. If you want to do it in one query, you can use insert select
I need to enter scores for all subjects offered by all students in a class simultaneously. So I retrieved the students ID, retrieved the list of subjects being offered by the students, and placed a textbox under each subject.
Now, I want to submit the score in the database as well as the subject name and the student ID, but the score is not storing, just the subject name and the student ID.
Here is my code:
<form method="post">
<?php
include "includes/dbcon.php";
$subject_name ="";
echo "<table border='1'><thead><tr><td>Students Name</td>";
$query_subjects = mysqli_query($link,"SELECT * FROM junior_subjects ORDER BY subject_name ASC");
while ($row_subject=mysqli_fetch_array($query_subjects))
{
$subject_name .= $row_subject['subject_name'];
echo "<td>".$row_subject['subject_name']."</td>";
}
echo "</tr></thead>";
$query_students = mysqli_query($link,"SELECT * FROM students WHERE class_cat='Junior'");
while ($row_students=mysqli_fetch_array($query_students))
{
$student_id = $row_students['student_id'];
echo "<tr><td>".$row_students['student_id']."</td>";
$query_subjects2 = mysqli_query($link,"SELECT * FROM junior_subjects ORDER BY subject_name ASC");
while ($row_subject2 =mysqli_fetch_array($query_subjects2))
{
$subject_name2 =$row_subject2['subject_name'];
echo "<td>
<input type='text' hidden name='$subject_name2'>
<input type='text' size='4' name='$subject_name2'>
</td>";
/////
if (isset($_POST['submit']))
{
$score = $_POST[$subject_name2];
mysqli_query($link,"INSERT INTO score_sheet(student_id,subject_name,score) VALUES('$student_id','$subject_name2','$score') ");
}
}
}
?>
<input type='submit' name='submit'>
</form>
You should have the input score as array and make a foreach loop to insert the query.
You should have the input field like this
And do a foreach loop like this
$score = $_POST['score'];
foreach ($score as $key)
{
$query = "INSERT INTO score_sheet(student_id,subject_name,score) VALUES('$student_id','$subject_name2','$key') ";
$query = mysqli_query($link,$query);
}
Note :
You should not have have two forms inside it.
I have made an eval for you
Warning :
It is not at all a good practise to have such a bulk entry.
I've been working on this for at least a month, and can't find this question elsewhere. I know I'm just missing something stupid, but...
There are 2 tables: biz and bizclass. bizclass.bizclassName holds the 250+ classifications to populate the dropdown box. Population from bizclass table and update to biz table both work, but when I try to select the current data from biz.bizClass1 , the dropdown initial value is set as the null value "Select Class". Please help. It's driving me bonkers. I'm too old for many more sleepless nights! Newbie - somewhat familiar with php and javascript but don't have a grip on ajax yet.
echo "Class1: <select name ='bizClass1' id='bizClass1'/> ";
$sql = 'SELECT bizclassName FROM bizclass ORDER BY bizclassName';
$query2 = 'SELECT `bizClass1` FROM `biz` WHERE `bizID` = "'. $search .'"';
$clist = mysqli_query($connection,$sql);
$num=mysqli_num_rows($clist);
$olist = mysqli_query($connection, $query2); // select bizClass from biz
$bizTblRecord = mysqli_fetch_assoc($clist); // option values from bizclass table to populate the dropdown
$row2 = mysqli_fetch_assoc($olist); // fetched the bizClass from biz
if ($row2['bizClass1'] == $bizTblRecord['bizclassName']){
printf ("<option value='%s' selected >%s</option> ", $row2['bizClass1'], $row2['bizClass1']);
} else {
printf ("<option value=''>Select Class</option> ");
}//end if
for($numrows=1; $numrows<= $num; $numrows++)
{
// Associative array
$row=mysqli_fetch_assoc($clist);
printf ("<option value='%s'>%s</option>",$row['bizclassName'],$row['bizclassName']);
} //end for
echo "</select>";
// Free result set
mysqli_free_result($clist);
mysqli_free_result($olist);
echo "Class1: <select name ='bizClass1' id='bizClass1'/>
<option value=''>Select Class</option> ";
$sql = 'SELECT bizclassName FROM bizclass ORDER BY bizclassName';
$clist = mysqli_query($connection,$sql);
$num=mysqli_num_rows($clist);
$querySEARCH = 'SELECT `bizClass1` FROM `biz` WHERE `bizID` = "'. $search .'"';
$SEARCHlist = mysqli_query($connection, $querySEARCH); // select bizClass from biz
$rowSEARCH= mysqli_fetch_assoc($SEARCHlist); // fetched the bizClass from biz
for($numrows=1; $numrows<= $num; $numrows++)
{
// Associative array
$row=mysqli_fetch_assoc($clist);
if ($rowSEARCH['bizClass1'] == $row['bizclassName']){
printf ("<option value='%s' selected >%s</option> ", $rowSEARCH['bizClass1'], $rowSEARCH['bizClass1']);
} else {
printf ("<option value='%s'>%s</option>",$row['bizclassName'],$row['bizclassName']);
}//end if
} //end for
echo "</select>";
// Free result set
mysqli_free_result($clist);
mysqli_free_result($SEARCHlist);
If statement have to be inside the loop to compare each option with search.
Test tables:
biz
bizID bizClass1
1 ronaldo
2 shevshenko
3 falcao
4 zidane
5 valderrama
bizclass
bizclassName
falcao
ozil
ronaldo
messi
shevshenko
valderrama
hazard
totti
I have 2 tables relating to a survey. When user answers each set of questions and then click the submit button, it will loop each answer according to the form submitted in order to check within the database first, if the CustomerID and QuestionID have been found, then do the Update. If not found, do the Insert instead.
QUESTIONS table
QuestionID (PK)
QuestionText
ANSWERS table
AnswerID (PK)
CustomerID (FK)
QuestionID (FK)
AnswerText
<html>
....
<form action="/db.php" method="POST">
<?php echo $questiontext[1]; ?><input type="text" name="answer1" id="answer1">
<?php echo $questiontext[2]; ?><input type="text" name="answer2" id="answer2">
<?php echo $questiontext[3]; ?><input type="text" name="answer3" id="answer3">
<?php echo $questiontext[4]; ?><input type="text" name="answer4" id="answer4">
<?php echo $questiontext[5]; ?><input type="text" name="answer5" id="answer5">
<?php echo $questiontext[6]; ?><input type="text" name="answer6" id="answer6">
<input type="submit" name="submit" id="submit" value="Submit">
</form>
...
</html>
db.php
<?php
if(isset($_POST['submit'])) {
$cusid = intval($_POST['CustomerID']);
$answer1 = $db->real_escape_string($_POST['answer1']);
$answer2 = $db->real_escape_string($_POST['answer2']);
$answer3 = $db->real_escape_string($_POST['answer3']);
$answer4 = $db->real_escape_string($_POST['answer4']);
$answer5 = $db->real_escape_string($_POST['answer5']);
$answer6 = $db->real_escape_string($_POST['answer6']);
$sql = "INSERT INTO Answers (CustomerID, QuestionID, AnswerText) VALUES
('".$cusid."','".$quesid."','".$answer."')";
$res = $db->query($sql) or die ('Error: ' . mysqli_error($db));
}
?>
My questions are:
How to update each answer(1-6) one by one and then insert into the database if CustomerID and QuestionID have not been found by using array and SQL query, if found, then just update?
How could I reference the QuestionID in order to related with AnswerText in HTML and PHP?
This is just an idea for you. Hope you can understand it. Make sure you replace database driven functions with your $db object.
if(isset($_POST['submit'])) {
$sql = "SELECT QuestionID FROM Questions ORDER BY QuestionID ";
$res = $db->query($sql);
$qus = 1;
while ($row = mysqli_fetch_array($res , MYSQLI_ASSOC)) {
{
$questionID = $row['QuestionID'] ;
$answer = $db->real_escape_string($_POST['answer' . $qus ]);
$sql = "SELECT AnswerID FROM Answers WHERE CustomerID='$cusid' AND QuestionID='$questionID' ";
$resAns = $db->query($sql);
$num_rows = $resAns->num_rows; // This should be replace with your $db object record count obtaining method
if($num_rows == 1)
{
$sql = "UPDATE Answers SET AnswerText = '$answer' WHERE CustomerID='$cusid' AND QuestionID='$questionID' ";
// Execute your update query
}
else
{
$sql = "INSERT INTO Answers (CustomerID, QuestionID, AnswerText) VALUES
('".$cusid."','".$questionID."','".$answer."')";
// Execute your insert statement
}
$qus ++;
}
}
You can run a select query first and then see how many rows have been returned from there something like this
$check = mysql_query("SELECT * FROM Answers WHERE CustomerId = '$cusid' OR QuestionId = '$quesid' LIMIT 1") or die(mysql_error());
$num_rows = mysql_num_rows($check);
if($num_rows == 1)
{
// value exists run the update
}
else
{
// go ahead with insert query
}
If you set a unique key on CustomerID+QuestionID, then you can just do an INSERT ... ON DUPLICATE KEY UPDATE ...
http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html
Let the database handle the checks.