0

Hello guys I have a problem with a script

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'site';
  $con = mysql_connect($dbhost, $dbuser, $dbpass);
    if (!$con)
    {
    die(mysql_error());
    }
mysql_select_db($dbname, $con);
$sql = "REPLACE INTO stiri (id, titlu, continut, link, categorie, data) VALUES   ('','$titlu','$text','$link','Liga 1','$data')"; 
mysql_query($sql);
mysql_close($con);

This part is in a php foreach part and every time I run the script I get duplicate entry, how can I prevent this? I could use UNIQUE Constraint but I want the link to be unique which is longer than 125 chars..

Ankur
  • 12,676
  • 7
  • 37
  • 67
  • 3
    Please don't use the deprecated mysql_ functions if you can help it. Use mysqli or PDO instead. – Patrick James McDougle Nov 14 '12 at 18:30
  • 2
    You shouldn't put all of that in a `for` loop. Creating and closing connections like that is unnecessary. Just create the connection, and put the statements you want to run in the `for` loop. – burmat Nov 14 '12 at 18:32
  • http://stackoverflow.com/questions/2219786/best-way-to-avoid-duplicate-entry-into-mysql-database =>i think this link will help you..... – Ankur Saxena Nov 14 '12 at 18:35
  • @AnkurSaxena i've seen that post, but i need the link to be unique wich is longer than 125 chars, is that a problem ? the server will run slower or.. – Cosmin Stan Nov 14 '12 at 19:01

1 Answers1

1

I'm guessing id is a primary key field in your table? You're trying to insert an empty string ('') into it. If that's an INT field, mysql will convert '' into 0. After the first such insert, you'll run into the duplicate key problem.

Change id to be an auto_increment field, and insert a null value, e.g.

REPLACE INTO stiri (id, ...) VALUES (null, ....)

so mysql can generate an ID for you automatically.

Marc B
  • 356,200
  • 43
  • 426
  • 500