SQL UPDATE查询通过MySQL Workbench正确执行,但不能通过PHP执行

时间:2013-05-22 00:19:09

标签: php mysql sql sql-update

我有以下SQL查询:

UPDATE uploads SET UserName='Test2', UserEmail='Test2', UploadCount='4' 
WHERE Country = 'Algeria'

当我通过My​​SQL工作台运行此查询时,它执行正常。

我试图通过网站/ PHP运行,但是我试图以下列方式执行查询:

$sql = "UPDATE uploads SET UserName='$user_data[name]', UserEmail='$user_data[email]', UploadCount='$user_data[FilesUploaded]' WHERE Country = '$country'";


echo $sql;  
    try 

    {
    $pdo = new PDO('mysql:host=localhost; dbname=db01', $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $pdo->prepare($sql);
    $stmt->execute();       

  # Affected Rows?
      echo $stmt->rowCount(); // 1
    } catch(PDOException $e) {
      echo 'Error: ' . $e->getMessage();
    }

SQL查询是通过这里的变量构建的,但是我将$ sql的echo复制/粘贴到workbench中以检查是否没有语法错误,$ sql的echo是我上面粘贴的。

当我通过Web应用程序运行它时,我受到0行影响并且没有更新UPDATE,我哪里出错了?

谢谢

更新:PDO的一个新的paramatarized版本:

$sql =  "UPDATE uploads SET ";

$sql .="UserName = :name, 
        UserEmail = :email, 
        UploadCount = :FilesUploaded";

$sql .=" WHERE Country = '$country'";

    try     
    {
    $pdo = new PDO('mysql:host=localhost; dbname=db01', $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $pdo->prepare($sql);

    $stmt->bindParam(":name", $user_data['name']);
    $stmt->bindParam(":email", $user_data['email']);
    $stmt->bindParam(":FilesUploaded", $user_data['FilesUploaded']);

    $stmt->execute();       

  # Affected Rows?
      echo $stmt->rowCount(); // 1
    } catch(PDOException $e) {
      echo 'Error: ' . $e->getMessage();
    }

1 个答案:

答案 0 :(得分:-1)

看起来你正试图在引号中插入数组中的信息。试试这个:

$sql = "UPDATE uploads SET UserName='".$user_data['name']."', UserEmail='".$user_data['email']."', UploadCount='".$user_data['FilesUploaded']."' WHERE Country = '$country'";