停止SQL插入重复项(php)
仅仅使用SQL语句似乎不可能做到这一点,因此我编写了一个php检查,脚本完全忽略了它$资源数组保存正确的数据停止SQL插入重复项(php),php,sql,database,oop,pdo,Php,Sql,Database,Oop,Pdo,仅仅使用SQL语句似乎不可能做到这一点,因此我编写了一个php检查,脚本完全忽略了它$资源数组保存正确的数据 public function handleUpdates($updates) { $stmt = $this->database->connect()->prepare("SELECT ? FROM users"); //<- $stmt->execute(["username"]); //<- $resource = $s
public function handleUpdates($updates) {
$stmt = $this->database->connect()->prepare("SELECT ? FROM users"); //<-
$stmt->execute(["username"]); //<-
$resource = $stmt->fetch(PDO::FETCH_ASSOC); //<-
foreach ($updates["result"] as $update) {
$text = $update["message"]["text"];
$args = $update["message"]["chat"]["username"];
if ($text === "/start") {
if ($resource['username'] !== $args) //this here is ignored
$this->database->add($args);
}
}
}
根据我对PDO/SQL的记忆,我不久前迁移到MVC/Doctrine,这部分似乎有点多余
$stmt = $this->database->connect()->prepare("SELECT ? FROM users"); //<-
$stmt->execute(["username"]); //<-
$update[message]的内容是什么?您是否尝试过调试,例如打印其内容?是否已忽略?那么$resource['username']和$args的值是什么?很可能您得到的值与预期值不同。请注意,表/列名不能绑定,但可以将它们列为白名单$resource与$resource不同此代码$resource['username']!==$args无效,因为$resource['username']是一个数组,$args我猜是一个字符串。如果要检查数组中是否存在用户名,请使用in_array或array_key_exists。由于我在whiletrue循环中运行此方法,因此这仍然会用一个相同的查询淹没数据库guess@danielserendipity那就差不多了,您不需要将return true放在这里的某个地方吗?看起来不像这样,因为它不能中断循环公共函数execute{while true{$t=$this->getlastch$this->getUpdates;$this->sendMessage$t[0],$t[1];$updates=$this->getUpdates;if count$updates[result]>0$this->handleUpdates$updates;sleep1;}}@DanielSerendipity使用whiletrue将无限期循环,除非您在while语句中放入条件或在循环中中断,因为这是聊天机器人,循环不能停止
$stmt = $this->database->connect()->prepare("SELECT username FROM users"); //<-
public function handleUpdates($updates) {
$stmt = $this->database->connect()->prepare("SELECT username FROM users WHERE username = ?");
$stmt->execute(array($update["message"]["chat"]["username"]));
$resource = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$resource) {
foreach ($updates["result"] as $update) {
$text = $update["message"]["text"];
$args = $update["message"]["chat"]["username"];
if ($text === "/start") {
$this->database->add($args);
}
}
}
}