0

So, I have this code which is supposed to update a value in database but it doesn't work, can anybody help me find out why is that?

$bitcoin = $_POST['bitcoin'];

        $dsn = 'mysql:host=127.0.0.1;dbname=user_db;charset=utf8';

        $conn = new PDO($dsn, $username1, $password);
        $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt= $conn->prepare("UPDATE users SET bitcoin = :bitcoin WHERE username = :username");
        $stmt->bindParam(':bitcoin', $bitcoin,PDO::PARAM_STR);
        $stmt->bindParam(':username', $username,PDO::PARAM_STR);
        $stmt->execute();
        $try = $conn->fetch(PDO::FETCH_ASSOC);
        if ($try) {
        array_push($success, "Bitcoin Wallet Adress updated successfully.");
        } else {
        array_push($errors, "Error updating Bitcoin Wallet Adress, please report this error to us.");
        }
        header('location: settings.php');
        $conn->close();```
  • You can't use `fetch()` on an update query since they don't return any records. – M. Eriksson May 04 '19 at 10:06
  • Oh, what should I do then I want to check if this worked and inform the customer? @MagnusEriksson – Anti-Social Elephant May 04 '19 at 10:08
  • Just a note on `$stmt->rowCount()`, which the answer in the above duplicate recommends, is that it will only return the number of rows that were actually changed, so if you update a record but none of the values are changed (you update it with the same values as it already contains), it will return zero. That could be solved by adding an "updated" column in your table which you always update with the current date/time. – M. Eriksson May 04 '19 at 10:13

1 Answers1

0

Maybe change

$try = $conn->fetch(PDO::FETCH_ASSOC);

to

$try = $conn->rowCount();

for detecting update record or not.

tiebob
  • 96
  • 6