php-pdo使用变量更新查询


php pdo update query with variables

我希望有人能指出我这次更新的错误所在,我尝试了各种方法,但似乎都无法正常工作,可能是一个简单的错误,但我似乎找不到。

function set_live($row_id, $mobile_number)
{
    global $conn;
    $live = 1;
    $sql = "
     UPDATE 
      connections 
     SET 
      live = :live, 
      voice_number = :mobile_number 
     WHERE 
      id = :row_id";
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':mobile_number', $mobile_number, PDO::PARAM_INT);
    $stmt->bindParam(':row_id', $row_id, PDO::PARAM_INT);
    $stmt->bindParam(':live', $live, PDO::PARAM_INT);
    $stmt->execute();
    echo "Record edited successfully";
    $conn=null;
}

$conn是PDO连接,可与SELECT等一起使用所有变量都是数字,所有回声OK,因此在函数中也是我可以在phpmyadmin中使用实际值运行查询,它工作正常

只需更换这一行

$stmt->bindParam(':mobile_number', $mobile_number, PDO::PARAM_INT);

用这个

$stmt->bindParam(':mobile_number', $mobile_number, PDO::PARAM_STR);

因为电话号码长度大于整数。

为什么不尝试使用数组?这种方法很可能对你有用:

    <?php
        function set_live($row_id, $mobile_number){
            global $conn;
            $live = 1;
            $sql    = "UPDATE connections SET live=:live, voice_number=:mobile_number WHERE id=:row_id";
            $stmt   = $conn->prepare($sql);
            $params = array(
                "live"          =>$live,
                "mobile_number" =>$mobile_number,
                "row_id"        =>$row_id,
            );
            $stmt->execute($params);
            echo "Record edited successfully";
            $conn=null;
        }