如何在PDO PHP中为所有输入添加POST请求 [英] How to add a POST request for all inputs in PDO PHP

查看:63
本文介绍了如何在PDO PHP中为所有输入添加POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following PHP PDO Update script, instead of having the inputs all hardcoded I would like to get the values from POST.

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

How can I modify the following script to update both name and link to POST input values?

 <?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
?>

推荐答案

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

To replace the hard-coded values with dynamic values coming from $_POST you can use prepared statements. First you need to make sure with isset that the values were sent to your script. Then you should prepared the SQL statement with placeholders and execute passing in the array with your data.

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

This sample script shows how it could be done:

// 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

If you are unsure about the correct use of PDO you can take a look at this well-acclaimed PDO guide https://phpdelusions.net/pdo

这篇关于如何在PDO PHP中为所有输入添加POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆