David19801
David19801

Reputation: 11448

adding new row to unique table

I have a table with a unique column 'a'. I want to add a row to it.

If the row I want to add has a 'a' value that is already in the table, then of course, due to the uniqueness of the column, it will not be added, else, it will be added. I need to check if the new row was added, which will then tell me if the 'a' value was already in the table or not.

Whats the most efficient way to check if the new entry has been added to the table or not?

EDIT - For measure, the worst case scenario so far is a count before and a count after...

Upvotes: 0

Views: 117

Answers (2)

Nicola Cossu
Nicola Cossu

Reputation: 56357

I meant something like this (silly example)

$conn = mysql_connect('bla bla bla');
if (!mysql_query("insert into my_table values ('b')")) {
    echo mysql_errno($conn) . ': ' . mysql_error($conn) . "\n";
 }
 else { 
 echo 'ok!';
}

Upvotes: 0

jeroen
jeroen

Reputation: 91734

I always use ON DUPLICATE KEY UPDATE for that (but I normally want to update rows when the unique key already exits...).

In PDO you can then get a return code with something like $stmt->rowCount() that gives a 1 for a new record and a 2 for an updated record.

Upvotes: 1

Related Questions