第二次使用POST值:supplier
时,脚本不会写入数据库。没有第二个实例,所有内容都会按预期写入。我在做什么错了?
$hostdb = 'localhost';
$namedb = 'dbname';
$userdb = 'username';
$passdb = 'password';
$charset = 'utf8';
if (isset($_POST['name'], $_POST['type'] , $_POST['number'] ,$_POST['supplier'] )) {
// Connect and create the PDO object
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
];
$conn = new PDO("mysql:host=$hostdb;dbname=$namedb;charset=$charset", $userdb, $passdb, $options);
try{
$conn->beginTransaction();
$stmt = $conn->prepare( ' INSERT INTO `Equipment` (name, type, number, supplier, status, managed_by )
VALUES (:name,:type,:number,:supplier,"Ready", :supplier) ' );
$stmt->execute([
'name' => $_POST['name'],
'type' => $_POST['type'],
'number' => $_POST['number'],
'supplier' => $_POST['supplier'],
]);
答案 0 :(得分:1)
3个选项:
:managedBy
。请参见下面的示例。 $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
?
代替命名参数(如注释中指出的那样)第二个选项($db->setAttribute...
)允许您多次使用同一标识符。取自https://stackoverflow.com/a/40682033/296555。此方法存在安全隐患。我会保持清楚,但将其留在此处作为将来读者的选择。
编辑
使用唯一标识符的示例:
// Notice that we're using a uniquely names placeholder: `:supplier` and `:managedBy`
$stmt = $conn->prepare( ' INSERT INTO `Equipment` (name, type, number, supplier, status, managed_by )
VALUES (:name,:type,:number,:supplier,"Ready", :managedBy) ' );
// Notice that we are referencing those uniquely named placeholders below
// but using the same data `$_POST['supplier']`.
$stmt->execute([
'name' => $_POST['name'],
'type' => $_POST['type'],
'number' => $_POST['number'],
'supplier' => $_POST['supplier'],
'managedBy' => $_POST['supplier'],
]);