我在我的PHP项目中使用MYSQL并且使用以下查询我有一个“奇怪的”(不确定我是无知的还是什么):
public function vote($user) {
$this->DB->prepare('INSERT INTO Ratings (Entry_ID, Rating, User) VALUES (:entry_id, :rating, :user);');
$this->DB->bind(':entry_id', $this->getID(), \PDO::PARAM_INT);
$this->DB->bind(':rating', 1, \PDO::PARAM_INT);
$this->DB->bind(':user', $user);
$this->DB->execute();
$this->votes++;
}
进入下表:
// Ratings table
$DB->prepare("CREATE TABLE IF NOT EXISTS Ratings ("
." Entry_ID int(11),"
." ID int(11) AUTO_INCREMENT,"
." Rating int(11),"
." User varchar(255),"
." PRIMARY KEY (ID),"
." FOREIGN KEY (User) REFERENCES Users(Username)"
." ON DELETE SET NULL ON UPDATE CASCADE,"
." FOREIGN KEY (Entry_ID) REFERENCES Entries(Entry_ID)"
." ON DELETE SET NULL ON UPDATE CASCADE"
.") CHARACTER SET utf8;");
$DB->execute();
上一张表用于存储用户投的每一票。
问题是,每次执行第一个查询(INSERT
)时,Ratings
表中都会创建多个行。
编辑:在ajax响应脚本中调用vote函数:
session_start();
$entry = new Entry();
switch(filter_var($_POST["action"])){
// Create Entry
case "create":
break;
// Delete entry
case "delete":
break;
// Rate entry
case "rate":
$entry->load($entry->decryptID(filter_var($_POST["entryId"])));
$validator = new Validator();
if($validator->checkRating(filter_var($_POST["rating"]), $entry->getEncryptedID(), filter_var($_SESSION["User"]))) {
$entry->vote($_SESSION['User']);
die();
$entry->save();
echo "OK";
} else {
echo "ERROR";
}
break;
default:
echo "ERROR";
break;
}