PHP, MySQL, Drupal, .htaccess, Robots.txt, Phponwebsites

19 Mar 2014

Avoid duplicate values storing in table using php and mysql

                       We can avoid duplicate values storing in table when we insert data to table. Because the duplicate entry is one of the main problem, while insert data into mysql table . We removed duplicate values using 'DISTINCT' key in mysql query, if it is present in table. We can check whether the value is present in table or not using PHP and Mysql before add data to table.

                        We can also avoid duplicate values storing in mysql table while inserting by primary key.

Consider following example. You've a database named with 'new' and table named with 'user'. You try to add names in user table. Now you've to check the values is present or not while you inserting. The table look like this:

Avoid duplicat values sotring in table using PHP at phponwebsites

Now you try to add name 'guru' again. You can check whether the name 'guru' is present in table or not using below PHP script.

$query=mysql_query("select * from user where name='".$name."' ") or die(mysql_error());
      $query1=mysql_query("insert into user values('".$name."')")  or die(mysql_error());
      echo'The name '.$name.' is already present in the user table';
<form method='post' action='#'>
name: <input type='text' name='name'>
<input type='submit' name='submit' value='Submit'>

               mysql_query() - execute the query and select if any similar values are present in table.                                    mysql_num_rows() - returns numeric value of selected rows. If its value is 0, then there is no similar values present in table. Otherwise the value is already present in table.
               you can also use  mysql_fetch_row() instead of mysql_num_rows().                       
                        If the value is present in table, it could not be stored in table. Now you can avoid duplicate entries in table using PHP and Mysql.
Related Post:

How to store values into mysql table using php