1

I have this variable $nombrecat and I want to INSERT it into the table categories in the column category. But before that I want to check if already exists. This is my current code:

$nombrecat = $_POST['crearcat'];

$cmd = $connect -> prepare('INSERT INTO  `categories` (`category`) VALUES (:nombrecat)');
$cmd ->bindParam(':nombrecat',$nombrecat);

$cmd -> execute();

I want to check if $nombrecat exists. If it does, do nothing, if it doesn't, execute my code above. How can I achieve this?

pedritoalfonso
  • 173
  • 1
  • 12
  • `WHERE NOT EXISTS` - Google "insert if not exists mysql" and you'll find all sorts of answers. – Funk Forty Niner Apr 03 '15 at 00:47
  • Is `category` the primary key of the table? You can use `INSERT IGNORE` to perform the insert and ignore the duplicate key error. – Barmar Apr 03 '15 at 00:48
  • @Fred-ii- You can't have a `WHERE` clause in an `INSERT` statement. – Barmar Apr 03 '15 at 00:48
  • Put an `UNIQUE` index on the `category` column and use `INSERT IGNORE`. – Sammitch Apr 03 '15 at 00:48
  • @Barmar http://stackoverflow.com/a/3025332/ – Funk Forty Niner Apr 03 '15 at 00:48
  • Sorry I don't understand all this "primary key" stuff. How does it work? – pedritoalfonso Apr 03 '15 at 00:53
  • @pedritoalfonso Another way to do it without using any of the answers from the duplicate link the question was closed with, is to use a conditional statement on SELECT. If a row exists, then tell write your code to exit after the query. `if(condition){ do something } else { do something else }`. Here's an answer on Stack that you can base yourself on to check if a row exists http://stackoverflow.com/a/11974650/ - You can also Google "if row exists mysql pdo". Or as already stated, modify your column to have a `UNIQUE` constraint. – Funk Forty Niner Apr 03 '15 at 01:00
  • Yes I've done this, selected all from categories where category = $nombrecat, and stored it in a variable, and the use count() to check wheter it's 0 or 1, thank you all for answering! – pedritoalfonso Apr 03 '15 at 01:14

0 Answers0