sql + php-在插入之前检查重复

时间:2018-06-01 05:14:07

标签: php mysql

我试图在插入一个语句之前检查重复项,并在查看一些帖子之后我仍然无法得到我的PHP出了什么问题,下面是我的代码,请让我知道如果我有我的PHP中的东西或者在我的sql中...谢谢!

date_default_timezone_set("America/Los_Angeles");
$time = date("y-m-d H:i:s");

//$name = $_POST["name"];
$name = "bulbasaur";
$lcname = strtolower($name);
if(empty($_POST["nickname"])) {
    $nickname = strtoupper($name);
} else {
    $nickname = $_POST["nickname"];
}



//Connect SQL & PHP
$host = getenv('IP');
$user = getenv('C9_USER');
$password = "";
$dbname = "hw7";

// Create connection
$ds = "mysql:host={$host};dbname={$dbname};charset=utf8";

// Make connection
try {
    $db = new PDO($ds, $user, $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);   
}
catch(PDOException $ex) {
    header("Content-Type: text/plain");
    echo "Can not connect to the database. Please try again later. \n";
    echo "Error details: $ex \n";
    die();
}

//check duplicates
$subsql = "SELECT name FROM Pokedex WHERE name = {$name})";
try {
$dupe = $db->prepare($subsql);
$param = array("name" => $name);
$dupe->execute($param);
}
catch(PDOException $ex) {
    die($ex->getMessage()."\n");
}
if($dupe-> rowCount() > 0) {
    echo "fail";
} else {
    $sql = "INSERT INTO Pokedex(name, nickname, datefound) 
        VALUES (:name, :nickname, :datefound);";
    try{
        $stmt = $db->prepare($sql);
        $params = array(":name" => $lcname, 
                ":nickname" => $nickname, 
                ":datefound" => $time);
        $stmt->execute($params);
    }
    catch(PDOException $ex) {
        die($ex->getMessage());
    }
}

我收到此错误消息 - 请帮助我......

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1

由于该消息提到了我的sql,这里是我的sql代码 -

DROP TABLE IF EXISTS Pokedex;
CREATE TABLE Pokedex(
  name          VARCHAR(30)     PRIMARY KEY,
  nickname      VARCHAR(30),
  datefound     DATETIME      
);

INSERT INTO Pokedex(name,nickname,datefound) VALUES 
("Pikachu","Pika","2018-01-03 12:23:44");

1 个答案:

答案 0 :(得分:0)

你有两个问题。

首先,您在查询结尾处有一个拼写错误,一个额外的)。这导致了语法错误。

其次,您使用$param = array("name" => $name);准备好的声明。因此,您不需要在查询中添加{$name},您必须放置一个占位符。

$subsql = "SELECT name FROM Pokedex WHERE name = :name";

或者,您可以尝试INSERT,而不是自己检查副本。如果名称重复,则会收到错误,您可以在catch块中检查此内容。

catch(PDOException $e) {
    if ($e->code == 2627) { // Violation of primary key constraint
        echo "fail";
    } else {
        die($ex->getMessage());
    }
}