doukuang1897 2012-09-04 12:13
浏览 34
已采纳

数据库:检查重复错误

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.

  • 写回答

1条回答 默认 最新

  • dpp34603 2012-09-04 12:17
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)