我有以下 SQL 查询:
UPDATE uploads SET UserName='Test2', UserEmail='Test2', UploadCount='4'
WHERE Country = 'Algeria'
当我通过 MySQL 工作台运行此查询时,它执行得很好。
但是,我正在尝试通过网站/ 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 的回声复制/粘贴到工作台中以检查是否没有语法错误出现,$sql 的回声是我在上面粘贴的。
当我通过 Web 应用程序运行它时,我受到 0 行影响并且没有进行更新,我哪里出错了?
谢谢
更新:PDO 的新参数化版本:
$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();
}