Page 1 of 1

While loop

Posted: Tue Feb 22, 2011 7:46 pm
by dixiestudent
Hi all,
im writing some php script to add records to my db. However, if a value thats about to be added already exists, then dont add that record.
for example: I have a table called assignment and a col that is called assignment_num which has the values of 71,72,73,74,75,76,77 and 78. Each value represents one assignment. If 71 and 72 are already in the db I want to insert only the next one which would be 73. I hope this make sense?

Below I have be able to check and see if they exists and print them out but cannot figure out how to only insert one from here.

Code: Select all



if ( $row['assignment_num'] >= "71" && $row['assignment_num'] <="78")
{ 
print $row[assignment_num] . "<br> "; 
	$row[assignment_num]++;
}  




Thanks,
DixieStudent

Re: While loop

Posted: Wed Feb 23, 2011 5:00 am
by social_experiment
It would be better to use a for loop. This will go inside your while loop.

Code: Select all

<?php
$value = 78;
while ($row = mysql_fetch_array($result)) {
 for ($i = 71; $i <= $value; $i++) {
  if ($row['assignment_num'] != $i) {
  // insert row
 }
}
?>
I'm guessing that the assignment number are not always 71 - 78 but will be incremented as the assignments increase? You would therefore have to change the for loop so that the 'checking' is done for the total amount of records you have.

Re: While loop

Posted: Wed Feb 23, 2011 10:02 am
by gooney0
You could attack this a few ways:

1) Fetch an array of assignment ids from the DB and check them before inserting.

2) Change your field in the DB to "unique" and insert everything. If that assignment id exists your query will effect 0 rows.

The for loop is alright so long as your assignment ids are sequential. You're in trouble if they are not.

I prefer foreach(). For method #1 i'd do something like:

Code: Select all

$existing_assignments= // mysql that fetches array of assignment ids

$incoming_assignments // an array of possibility new assignments

foreach($incoming_assignments as $id)
    {
    if(!in_array($id, $existing_assignments))
        {
        // This is new.  Do your insert using the $id array
        }

    }
For method #2 you just attempt to insert each of the $incoming_asignments. You can use mysql_insert_id to test if you want to know whether an new row was created.