Kartik Deshpande Kartik Deshpande - 5 months ago 14
MySQL Question

Return data that was not inserted in mysql table

I have a

.csv
file which will insert data into a table through the following PHP code

while (($col = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$quer = "INSERT INTO table1(username, password) VALUES('$col[0]','$col[1]')";
mysql_query($quer);
}


The username is the primary key so it should be unique. Now if the table already contains "abc" as a username and the
.csv
file is inserting "abc" again in the username column, the query won't be executed as it's primary!

Now how can I insert all unique usernames and display the ones which were not inserted from the
.csv
file?

Answer

As you said username is primary key column in your table. And you want to display those records which are not inserted (due to duplicate username).So do like below:-

$failed_data = array();  // create an empty array
while (($col = fgetcsv($handle, 1000, ",")) !== FALSE) { 
     $quer="INSERT into table1(username,password)values('$col[0]','$col[1]')"; 
     if(!mysql_query($quer)){  // check if query run
       $failed_data[] = array($col[0],$col[1];) // if not assign failed value to array
     } 
}
echo "<pre/>";print_r($failed_data);//print the array

Note:- Please read @Alex answer and follow instructions. Necessary

A note on the mysql_* library functions: Don't use them! They are deprecated as of PHP 5.5, and removed as of PHP 7! If you are learning from a tutorial, do consider reporting it to @halfer's Awooga database.

Comments