Dan P.
Dan P.

Reputation: 1775

PDO debugging update query using bindValue

I'm using PDO and I can't find what's wrong in there and can't seem to get an error even if PDO's setAttribute is set to.

    $fields = $data['fields'];
    $cartID = $data['cartID'];

    $sql = "UPDATE ShoppingCart 
            SET shipToSameLocation_shippingLocationID = :shippingLocationID, shipToSameLocation_shippingMethod = :shippingMethod, shipToSameLocation = 1
            WHERE cartID = :cartID";
    $query = $conn->prepare($sql);
    $query->bindValue(':shippingLocationID', $fields['shipToSameLocation_shippingLocationID'], PDO::PARAM_INT);
    $query->bindValue(':shippingMethod', $fields['shipToSameLocation_shippingMethod'], PDO::PARAM_STR);
    $query->bindValue(':cartID', $cartID, PDO::PARAM_INT);
    $query->execute();

Anything wrong in there related to PDO?

Upvotes: 0

Views: 1346

Answers (1)

David Soussan
David Soussan

Reputation: 2736

Proabaly because you are explicitly saying that the value will be an int but not coercing the post value into and int;

$fields = $data['fields'];
$cartID = (int) $data['cartID'];

$sql = "UPDATE ShoppingCart 
        SET shipToSameLocation_shippingLocationID = :shippingLocationID, shipToSameLocation_shippingMethod = :shippingMethod, shipToSameLocation = 1
        WHERE cartID = :cartID";
$query = $conn->prepare($sql);
$query->bindValue(':shippingLocationID', $fields['shipToSameLocation_shippingLocationID'], PDO::PARAM_INT);
$query->bindValue(':shippingMethod', $fields['shipToSameLocation_shippingMethod'], PDO::PARAM_STR);
$query->bindValue(':cartID', $cartID, PDO::PARAM_INT);
$query->execute();

The same goes for the other values you are binding so cast them to their correct type, or better yet don't use bind value. Personally I have never bothered to bind params or values, I just pass an associative array into PDO.

$locId = (int) $fields['shipToSameLocation_shippingLocationID'];
$method =  $fields['shipToSameLocation_shippingMethod'];
$cartId = (int) $data['cartID'];
$params = array(
    ':shippingLocationID' => $locId ,
    ':shippingMethod' => $method,
    ':cartID' => $cartId
);
$query->execute($params);

works for like a charm every time. Most places I work, the other people end up adopting this method because it is so much less trouble to code and to use, but it is up to you.

Upvotes: 1

Related Questions