52

I am getting an error when updating a database using PDO. I am new to PDO so maybe the problem is a small one and I just don't understand. Funny thing about the error, the command works fine and the database does actually get updated. But it still returns an error back at me.

Code:

try {
    $stmt = $pdo->prepare("UPDATE $page SET $section = :new_content WHERE $section = '$old_content'");
    $stmt->execute(array(
        'new_content' => $new_content
    ));
    $result = $stmt->fetchAll();
    echo "Database updated!";
}
catch(PDOException $e) {
    echo 'ERROR UPDATING CONTENT: ' . $e->getMessage();
}

Error: ERROR UPDATING CONTENT: SQLSTATE[HY000]: General error

I literally have no idea where the problem could be because its very vaque and I haven't been able to find anyone with the same problem.

Jocelyn
  • 11,209
  • 10
  • 43
  • 60
jagershark
  • 1,162
  • 3
  • 15
  • 27
  • 5
    You're vulnerable to SQL injection, even though you're (partially/incorrectly) using prepared statements and placeholders. Just because YOU'RE the one providing the data being insert doesn't mean you can't inject yourself. – Marc B Oct 19 '12 at 17:38
  • Are you referring to the variables $page & $section? They are both taken from the fixed ID of html elements. so you are saying even they are potentially harmful? – jagershark Oct 19 '12 at 17:39
  • 4
    `$old_content` would be the big red flag for me. **ANY** dynamic data going into a query string is potentially harmful. just because you pulled it out of a DB doesn't mean it's safe. e.g. consider something like `update users set name='Miles T. O\'Brien' where name='Miles O'Brien';`. you escape the newly updated name, but pulled the original name from the db to begin with, and now you've injected yourself a syntax error. – Marc B Oct 19 '12 at 17:42
  • Ah yes ok. I never thought of that. Thanks Marc. – jagershark Oct 19 '12 at 17:44
  • 3
    You are trying to fetch an UPDATE query – Ruwantha Aug 06 '14 at 10:14
  • @Ruwantha How do you do that? – AlxVallejo Mar 01 '16 at 16:30
  • @AlxVallejo $pdo->prepare("SELECT.... not $pdo->prepare("UPDATE.... – Ruwantha Mar 02 '16 at 17:00
  • In other words, there's no succinct way to return rows from an update query? – AlxVallejo Mar 02 '16 at 17:38

2 Answers2

113

You do not use fetchAll(),as in

$result = $stmt->fetchAll();

with update or insert queries. Removing this statement should rectify the problem.

TranQ
  • 1,381
  • 1
  • 9
  • 10
14

Just to note, another possible reason for this error is if you make a second database call with the variable $stmt inside of an existing parent $stmt loop.

     $stmt = $conn->query($sql);

    while ($row = $stmt->fetch()) {  //second use of $stmt here inside loop
Acyra
  • 15,864
  • 15
  • 46
  • 53