0

I'm trying to convert all my non-prepared queries into prepared statements.

In the following code I have commented out the working old query, above it is the new prepared statement. However it's not working for me. Does anyone see anything wrong with this?

<?php
require_once 'pdocon.php';

if (isset($_POST['card_id'])) {
    $card_id = ($_POST['card_id']);
    $rowname = ($_POST['rowname']);
    $rowothervalue = ($_POST['rowothervalue']);

    $stmt = $conn->prepare("UPDATE cards SET :rowname = :rowothervalue WHERE id= :card_id");

    $stmt->bindParam(':rowname', $rowname);
    $stmt->bindParam(':rowothervalue', $rowothervalue);
    $stmt->bindParam(':card_id', $card_id);

    $stmt->execute();

    // $status_sql='UPDATE cards SET '.$rowname.' = '.$rowothervalue.' WHERE id=' . $card_id . '';
    // $status_result = $conn->query($status_sql);
}

$conn = null;
?>
ragoutje
  • 35
  • 1
  • 8
  • 1
    You can't use placeholders for column names, they can only be used where expressions are allowed. – Barmar Jun 23 '15 at 18:05
  • So you need to use concatenation for `$rowname`. – Barmar Jun 23 '15 at 18:06
  • Thanks Barmar and Fred -ii-. I placed the variable for the columnname directly into the sql and it works. But isn't the use of bindParam needed in this case? I could just as easily place all the variables in the sql directly `UPDATE cards SET $rowname = $rowothervalue WHERE id= $card_id` and still prepare it. Is this as safe? – ragoutje Jun 23 '15 at 18:23
  • You should still use `bindParam` for `$rowothervalue` and `$card_id`. If you don't, you should use `$conn->escape()` to escape it. – Barmar Jun 23 '15 at 18:26

0 Answers0