Thursday 15 July 2010

mysqli - How to avoid duplicate entry in mysql with php -


Here I have created a function to generate random keys,

  function gen_link ( ) {$ Link = ''; $ S = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; For ($ i = 0; $ i & lt; = 4; $ i ++) $ link = $ link $ S [Rand (0, 63)]; $ Link returned; }   

I do not want to repeat the key in the mysql table, I have made it unique in mysql, but what do I have to do, when the key already exists, then i will have another random : I want to generate the key and try to add it to the table again, I have tried this code below.

  $ con = mysqli_connect ("localhost", "shashi", "asd123", "redir"); $ Sql ​​= "Enter in the 'link' ('link') value ('$ link')"; Do {$ link = gen_link (); $ Result = mysqli_query ($ conn, $ sql); } While (mysqli_errno ($ thief) == 1064); Mysqli_close ($ thief);   

But it does not work at all, it keeps looping. What can i do

Instead of generating a real error, use a query like this:

 $ sql = "` link` (`link`) values ​​('$ link')";   

And make sure something is actually inserted:

  while (mysqli_affected_rows ($ con) == 0);   

All together, it looks like this:

  $ con = mysqli_connect ("localhost", "shashi", "asd123", "redir "); Do {$ link = gen_link (); Ignore $ Sql ​​= "` link` (`link`) values ​​('$ link')"; $ Result = mysqli_query ($ conn, $ sql); } While (mysqli_affected_rows ($ con) == 0); Mysqli_close ($ thief); In addition, a couple notes about your inquiries:  
  1. I have created my quotes around table and column names

  2. Because you are including the $ link variable directly in the query, you have to define your query Required After you assign a value to the $ link variable - so I took that line inside the loop. This is probably the source of your original problem where you had looping.

  3. This is not important in this example because you have full control of the value that you are going to enter ( gn_link () ), but Alternatively, read a little bit, and use them instead, to come into the habit of avoiding the variables inserting in a query.

No comments:

Post a Comment