如何在PDO PHP中为所有输入添加POST请求

时间:2019-06-20 16:19:23

标签: php sql pdo

我有以下PHP PDO Update脚本,而不是所有输入都经过硬编码,我想从POST获取值。

如何修改以下脚本以更新名称和POST输入值的链接?

 <?php
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'tests';
$userdb = 'username';
$passdb = 'password';

try {
  // Connect and create the PDO object
  $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
  $conn->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8

  // changes data in "name" si "link" colummns, where id=3
  $sql = "UPDATE `sites` SET `name`='Spanish Course', `link`='marplo.net/spaniola' WHERE `id`=3";
  $count = $conn->exec($sql);

  $conn = null;        // Disconnect
}
catch(PDOException $e) {
  echo $e->getMessage();
}

// If the query is succesfully performed ($count not false)
if($count !== false) echo 'Affected rows : '. $count;       // Shows the number of affected rows
?>

2 个答案:

答案 0 :(得分:0)

要将硬编码的值替换为来自$_POST的动态值,可以使用准备好的语句。首先,您需要使用isset确保将值发送到脚本。然后,您应该使用占位符准备SQL语句,并执行将数据与数组一起传递。

此示例脚本显示了如何实现:

// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'tests';
$userdb = 'username';
$passdb = 'password';
$charset = 'utf8'; // you should be using utf8mb4 instead

if (isset($_POST['name'], $_POST['link'], $_POST['id'])) {
    // 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);

    // changes data in "name" si "link" colummns, where id=3
    $stmt = $conn->prepare('UPDATE `sites` SET `name`=:name, `link`=:link WHERE `id`=:id');
    $stmt->execute([
        'name' => $_POST['name'],
        'link' => $_POST['link'],
        'id' => $_POST['id'],
    ]);

    // Shows the number of affected rows
    echo 'Affected rows : '. $stmt->rowCount();
}

如果您不确定PDO的正确使用方法,可以查看这份备受赞誉的PDO指南https://phpdelusions.net/pdo

答案 1 :(得分:-2)

您可以使用POST['']属性从POST请求中获取信息。

<?php
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'tests';
$userdb = 'username';
$passdb = 'password';

try {
  // Connect and create the PDO object
  $conn = new PDO("mysql:host=$hostdb; dbname=$namedb; charset=utf8", $userdb, $passdb);

  // changes data in "name" is "link" colummns, where id=3
  $sql = "UPDATE `sites` SET `name`=':name', `link`=':link' WHERE `id`=3";
  $conn->prepare($sql);
  $count = $conn->exec(array('name' => $_POST['name'], 'link' => $_POST['link']));
  $conn = null;        // Disconnect
}
catch(PDOException $e) {
  echo $e->getMessage();
}

// If the query is succesfully performed ($count not false)
if($count !== false) echo 'Affected rows : '. $count;       // Shows the number of affected rows
?>

通知,我使用了准备好的查询语句。这样可以防止SQL Injection