PDO使用bindValue调试更新查询

时间:2015-03-18 04:24:26

标签: php mysql pdo

我正在使用PDO而且我找不到那里的错误,即使PDO的setAttribute设置为,也似乎无法收到错误。

    $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();

那里有什么问题与PDO有关吗?

1 个答案:

答案 0 :(得分:0)

Proabaly,因为你明确地说这个值是int而不是将post值强制转换为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();

您绑定的其他值也是如此,因此将它们转换为正确的类型,或者更好,但不要使用绑定值。就个人而言,我从不打扰绑定参数或值,我只是将一个关联数组传递给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);

每次都像魅力一样。我工作的大多数地方,其他人最终采用这种方法,因为编码和使用它的麻烦要少得多,但这取决于你。