Avoid data repetition MySQL
MySQL SELECT DISTINCT Statement is used to avoid data repetition in tables.Following table was created for example.Using SELECT Statement following results were obtained.
CREATE TABLE IF NOT EXISTS `lname` ( `ID` int(40) NOT NULL AUTO_INCREMENT, `FirstName` varchar(40) NOT NULL, `LastName` varchar(40) NOT NULL, PRIMARY KEY (`ID`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 ROW_FORMAT=FIXED AUTO_INCREMENT=7 ; -- -- Dumping data for table `Lname` -- INSERT INTO `Lname` (`ID`, `FirstName`, `LastName`) VALUES (1, 'David', 'Jackson'), (2, 'Michel', 'Jackson'), (3, 'Pamela', 'Hontor'), (4, 'Jude', 'Hontor'), (5, 'Mark', 'Tailar'), (6, 'Jack', 'Peter'); | <?php echo "<center><table bgcolor=#0b2d04> <tr bgcolor=#327423> <th><font color=#ffffff>Last Name</font></th> </tr>"; $username="root"; $password=""; $database="my_database"; mysql_connect(localhost,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $query ="(SELECT LastName FROM Lname)"; $result = mysql_query($query); while($row = mysql_fetch_assoc($result)){ echo "<tr bgcolor=#d7eecb> <td>" .$row['LastName']."</td> </tr>"; } echo "</table></center>"; ?> |
|
You will be noticed There are 2
Jackson and 2 Hontor in above table.This could be avoid using SELECT DISTINCT Statement see below example.
<?php echo "<center><table bgcolor=#0b2d04> <tr bgcolor=#327423> <th><font color=#ffffff>Last Name</font></th> </tr>"; $username="root"; $password=""; $database="my_database"; mysql_connect(localhost,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $query ="(SELECT DISTINCT LastName FROM Lname)"; $result = mysql_query($query); while($row = mysql_fetch_assoc($result)){ echo "<tr bgcolor=#d7eecb> <td>" .$row['LastName']."</td> </tr>"; } echo "</table></center>"; ?> |
|
No comments:
Post a Comment