Hello, Savior(s)!

I have been given a task to do the following:

"Assume that you have a database with a table named "trainer" with fields (trainerID, userName, fullName, email):

- create this DB and table then insert some random data manually

- create sql query to check if there any duplicate email for different users.
(check all table - hint: use while)

If there are any duplications:

- merge the data by adding the missing data to the old user "ID"

- delete the newest user "ID"

I am required to write the code for a general case scenario where if there exists two rows with the same email, my code should check to see if the rest of the field values are the same or not. Meaning that whatever code I'm going to write can be applied to this table "trainer" and any other table.

My code should be able to see if any users have the same email and remove any duplications found. Where:

If all the field values are the same, do nothing.

If not, then modify the data field values in the oldest row by writing the values from the newest row onto the original data of the oldest row and deleting the newest row.

-------------------------------
Here is my code:

while($q1=mysql_query("select * from trainer"))
{
	$email=$q1['email'];
	
	$q2=mysql_query("select * from trainer where email=$email");
	
	$numFields = mysql_query("select * from trainer where email=$email"); //
	
	$count=mysql_num_fields($numFields);
	
	echo $count."<br>"; //to test
	
	if($count>1)
	{
		$q3=mysql_query("select * from trainer where email=$email");
		
		while($row2=mysql_fetch_array($q3))
		{
			for($i=0;$i<$count;$i++)
			{
				if($row[$i]!=$row2[$i])
				{
					$new=$row2[$i]; //take data
				}
				else
				{
					$new=$row[$i]; //keep old
				}
			}//end for
		
		}//end inner while
	
	}//end if	
	
	//updating row	
	//$updateRow = mysql_query("UPDATE trainer($row)
		    				  //SET $new
		    				  //WHERE "); 
// insert modified data row into 'trainer' table   <---------- I have no idea how to update en ENTIRE row altogether without specifying each field
		    
    //delete newest row
    mysql_query("DELETE $row
		    	 FROM trainer
		    	 WHERE email=$new['email']")
    or die(mysql_error()); 

}//end outer while

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

Can anyone help me by looking over my code and letting me know what I'm doing wrong?

- Thank you.

P.S.: I am a complete beginner in programming in PHP.

Recommended Answers

All 7 Replies

Is this your entire code?
'cause i see some references to $row as an array, but i don't actually see you define it.
Secondly, you're using $row in your final mysql_query, but since it's an array, that won't work.
Also, you're inserting a variable between " " making it a string. so right now, it is trying to delete a record in the column $row (litteraly) where the column email is litteraly $new.

for example:

echo ("this is a $string");// is wrong
echo ("this is a " . $string);// is right

finally, i'm not quite sure wether this is the right syntax for a delete record: i'd advice checking php.net just to be sure

This is my entire code:

<?php
 <?php
 $link = mysql_connect('localhost') or die('Could not connect: '.mysql_error()); // open connection

	if(mysql_select_db('test')) // Check if connection to database 'test' is successful
	{
		echo "Connected to trainer database!<br><br>";
	}

$q1 = mysql_query("SELECT *
                   FROM trainer");
                       
$num_rows = mysql_num_rows($q1);

echo "Number of rows = ".$num_rows."<br><br>----------------<br>"; 

while($row = mysql_fetch_array($q1)) // display entire data [ WITH DUPLICATIONS ]
	{
    	echo "trainerID: ".$row['trainerID']."<br>";    
    	echo "userName: ".$row['userName']."<br>";
    	echo "fullName: ".$row['fullName']."<br>";
    	echo "email: ".$row['email']."<br><br>";
    
  	} 


    				       				         				   
while($row1 = mysql_fetch_array($q1) )
{
        
    $Email1= $row1['email'];
    $id=  $row1['trainerID'];
    
   $q2 = mysql_query("SELECT COUNT(email) 
    				  FROM trainer
    				  WHERE email= '$email'");  //number of duplications
    					 
    $count = count($q2); //count fields
    
    echo $count."<br>"; // test
    
    if($count>=1)
	{
    	while ($row2 = mysql_fetch_array($q2))
     	{  
			
			for($i=0;$i<$count;$i++)
			{
				if($row1[$i]!=$row2[$i])
				{
					$new=$row2[$i]; //take data
				}
				else
				{
					$new=$row1[$i]; //keep old
				}
			}//end for
		   
		  
		  $tID=$new['trainerID'];
		  $uname=$new['userName'];
		  $fname=$new['fullName'];
		  $e=$new['email'];
		  
		  
		    $updateRow = mysql_query("INSERT INTO trainer
		    				          VALUES ('$tID','$uname', '$fname','$e')"); // insert modified data row into 'trainer' table
		    
	 		mysql_query("DELETE FROM trainer
		    	         WHERE email='$Email1' && trainerID='$id1'")or die(mysql_error()); //delete old
		    	         
		   mysql_query("DELETE FROM trainer
		   				WHERE (email='$Email1') AND (trainerID > '$id')") or die(mysql_error()); //delete duplicate

         }//end while 
        
    }//end if    
    	
} // end while

mysql_close($link);


?>

I fixed the delete syntax and everything is correct except that there is still no change in the database rows.

Note:

I know that my code is a mess.

If you switch between a String (or something between " ") and something else (a variable, in this case) it needs to be seperated by a dot, just as in my last example.

This goes for practically everything in php: queries, echoes, etc...

Member Avatar for diafol

OK,

using the code I got from my link:

$rs = mysql_query("UPDATE tablename AS t JOIN (SELECT MinID, b.name AS latestname, b.surname AS latestsurname FROM tablename AS b JOIN (SELECT MIN(trainer_id) AS MinID, MAX(trainer_id) AS MaxID FROM tablename AS g GROUP BY email HAVING COUNT(*) > 1) g ON b.trainer_id = g.MaxID) rs ON t.trainer_id = rs.MinID SET t.name = latestname, t.surname=latestsurname");

$rs = mysql_query("DELETE t.* FROM tablename AS t LEFT JOIN (SELECT MIN(trainer_id) AS MinID FROM tablename AS g GROUP BY email) g ON t.trainer_id = g.MinID WHERE g.MinID IS NULL");

Tried it and it worked.

You now update the first record with the last record details, then delete all duplicates, leaving the first entry.

I assumed fieldnames: trainer_id, name, surname, email with the onus on email to identify duplicate entries
I used tablename in the sql above, change it to the name of your table.

This worked like a charm. Thank you! :)

Member Avatar for diafol

Great, if it's solved, click the link below the edit box. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.