我希望有人能帮助我解决这个问题。我在这里发现了一篇文章,允许用户在文本框中输入单词,并用逗号分隔,它将每个单词单独添加到 MySQL 数据库中。我尝试编辑它以匹配我拥有的表格,但它不起作用。
这是 PHP/HTML:
<?php
//Connect safely to your database
try {
$db = new PDO("mysql:host=localhost;dbname=DBNAME", 'USER', 'PASSWORD');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die('Cannot connect to mySQL server. Details:'.$e->getMessage());
}
$i=1;
if ($_SERVER['REQUEST_METHOD']=='POST' && !empty($_POST['words'])) {
$sql = "INSERT INTO rank (id, rank, position) VALUES ('$i', ':word', '$i')";
$stmt = $db->prepare($sql);
$stmt->bindParam(':word', $word);
foreach (explode(',', $_POST['words']) as $word) {
$word = trim($word);
if (empty($word)) {
continue;
}
$stmt->execute();
$i++;
}
}
//Your form
?>
<h1>Words</h1>
<form method="POST" action="">
<input type="text" name="words"/>
<input type="submit" name="submit" value="Submit"/>
</form>
Rank 表的 id 为自动递增 int(10),rank 为 varchar(50),position 为 int(10)。 id 和位置应依次增加 1、2、3 等。排名 1 为 [1, 排名 1, 1],排名 2 为 [2, 排名 2, 2],依此类推...
我不断得到:
[19-Aug-2016 10:49:14 America/Chicago] PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'PRIMARY'' in /home/wiredtutorial/public_html/ranks.php:26
Stack trace:
#0 /home/wiredtutorial/public_html/ranks.php(26): PDOStatement->execute()
#1 {main}
thrown in /home/wiredtutorial/public_html/ranks.php on line 26
最佳答案
发生错误是因为您尝试输入已存在的id
。您在查询中输入的 $i
不是像 :word
这样的绑定(bind)参数。这是一个硬编码值。因此,在循环中使用 $i++
增加它对下一个查询没有影响。
如果您的 id
字段设置为自动递增,请勿在查询中提供它。数据库将为您设置。
至于位置,它应该绑定(bind)到一个变化的参数,如:word
。
$sql = "INSERT INTO rank (rank, position) VALUES (:word, :pos)"
$stmt = $db->prepare($sql);
$stmt->bindParam(':word', $word);
$stmt->bindParam(':pos', $pos);
$pos = 0;
foreach (explode(',', $_POST['words']) as $w){
$word = trim($w);
if(empty($word)) continue;
$pos++;
$stmt->execute();
}
关于php - 根据用户输入将排名添加到 mysql 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39043566/