0

I have a PHP code and a field in the database which is a unique field. If people fill in the form and if the $_POST['name'] is already in the database it gives an error.

That's what I have and want, but now I want to check if there's an error so I can handle it in a if / else statement.

This is my code:

$db = new database();
$sql = "INSERT INTO product_groepen (name) VALUES (".$_POST['name'].")";
$result = $db->executeQuery($sql);
if ($result)
{
    $db->executeQuery($sql);
    $page .= 'Yes';
} else {
    $page .= 'No';
}

The error:

Warning: PDO::query() [pdo.query]: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 's' for key 2 in /classes/database.class.php on line 26

It works, and when it isn't working it says 'no', but the error remains.

Littm
  • 4,923
  • 4
  • 30
  • 38
Marnix
  • 303
  • 1
  • 3
  • 14
  • whats in `/classes/database.class.php on line 26` ? –  Sep 04 '12 at 12:15
  • return $this->handleDB->query($query); – Marnix Sep 04 '12 at 12:16
  • You could possibly use the mysql `insert ... on duplicate key update` syntax - to get past this. – Fluffeh Sep 04 '12 at 12:17
  • can you show what's inside your query($query) function?? – Sibu Sep 04 '12 at 12:23
  • **Your code is vulnerable to SQL injection.** You *really* should be using [prepared statements](http://stackoverflow.com/a/60496/623041), into which you pass your variables as parameters that do not get evaluated for SQL. If you don't know what I'm talking about, or how to fix it, read the story of [Bobby Tables](http://stackoverflow.com/questions/332365/xkcd-sql-injection-please-explain). – eggyal Sep 04 '12 at 12:31

1 Answers1

2

try with INSERT IGNORE to ignore insert if it's duplicate. Also if you are still using mysql_* you have an mysql injection vulnerability, escape it:

$db = new database();
$sql = "INSERT IGNORE INTO product_groepen (name) VALUES ('".mysql_real_escape_string($_POST['name'])."')";
$result = $db->executeQuery($sql);
$affected = mysql_affected_rows($result); // you must have that function something like $db->affectedRows ?
if ($affected){
    $page .= 'Yes';
} else {
    $page .= 'No';
}

and make sure you don't execute the query twice

Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107