我是PDO和php的新手。我想从一个表移动到另一个表,并使用我发送到下面脚本的链接。
LINK " id"在invtable中用作主键,(参见下面脚本中的FROM invtable)
提交的广告-florida.php?ID = 01820007985
SCRIPT submit-ads-florida.php
<?php
$host = "localhost";
$user = "user";
$password = "pass";
$database_name = "db";
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
$barCode = $GET['id'];
$query = "INSERT INTO adstable (Brand, Description, Price, Size, Price, Barcode)
SELECT Brand, Description, Price, Size, Price, Barcode FROM invtable
WHERE Barcode='".$barCode."'";
$pdo->query($query);
?>
问题
通过GET [id]删除了额外的括号。我收到以下错误。
致命错误:未捕获的异常&#39; PDOException&#39;消息&#39; SQLSTATE [42000]:语法错误或访问冲突:1110列&#39;价格&#39;指定两次&#39;在/home/myaccount/public_html/florida-ave/submit-ads-florida.php:16堆栈追踪:#0 /home/myaccount/public_html/florida-ave/submit-ads-florida.php(16):PDO- &gt;查询(&#39; INSERT INTO flo ...&#39;)在第16行的/home/myaccount/public_html/florida-ave/submit-ads-florida.php中抛出#1 {main}
更新
我更正了Price的多个条目。没有数据添加到adstable,我没有收到任何错误。
答案 0 :(得分:2)
好的,你有的问题是:
$barCode = $GET['id']);
应该是$barCode = $GET['id'];
,甚至可能是$_GET['id'];
SELECT
查询选择了两次(SELECT Brand, Description, >Price<, Size, >Price<)
INSERT INTO adstable (Brand, Description, >Price<, Size, >Price<
让我们来解决问题:
$barCode = isset($_GET['id']) ? $_GET['id'] : null;//avoids undefined index notice
接下来,要在SELECT
查询中两次使用相同的字段,您可以定义一个别名,但您不需要两次相同的字段...
SELET SELECT Brand, Description, Price as price_1, Size, Price as price_2, Barcode FROM
然后,为了防止一级注入攻击,让我们使用预备语句,而不是使用GET参数调用PDO::query
:
$stmt = $pdo->prepare('INSERT INTO adstable (Brand, Description, Price, Size, Barcode)
SELECT Brand, Description, Price, Size, Barcode FROM invtable
WHERE Barcode=:barcode'
);
$stmt->execute([':barcode' => $barCode]);
代码应该是这样的:
$barCode = isset($_GET['id']) ? (int) $_GET['id'] : null;
// check $barCode is valid value, if not, don't bother connecting
if ($barCode) {
$pdo = new PDO(
sprintf(
'mysql:host=%s;dbname=%s;charset=utf8', // add charset here!
$host,
$dbName
),
$user, $password,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]
);
$stmt = $pdo->prepare(
'INSERT INTO adstable(Brand, Description, Price, Size, Barcode)
SELECT Brand, Description, Price, Size, Barcode FROM invtable
WHERE Barcode = :barcode'
);
$stmt->execute(
[
':barcode' => $barCode
]
);
}
这应该可以解决问题。但严重的是:错误消息告诉您出了什么问题 阅读
答案 1 :(得分:-1)
请检查并更正此行:$barCode = $GET['id'];
如果这不是您的解决方案,请告诉我。