Skip to content Skip to sidebar Skip to footer

How To Add A Post Request For All Inputs In Pdo Php

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

Solution 1:

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 insteadif (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 rowsecho'Affected rows : '. $stmt->rowCount();
}

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

Solution 2:

You can use the POST[''] properties to get the information from a POST request.

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

Notice that I used the prepared query statement. This provides protection from SQL Injection.

Post a Comment for "How To Add A Post Request For All Inputs In Pdo Php"