在一个PHP文件中运行2个MySQL更新查询

时间:2016-01-02 17:47:46

标签: php mysql mysqli

我尝试运行

// Create connection
$conn = new mysqli($servername,$username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 
$sql = "UPDATE pm_videos SET `description` = REPLACE(  `description` ,'Facebook',  '')";
$sql = "UPDATE pm_videos SET `description` = REPLACE(  `description` ,'Twitter',  '')";

if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " .  $conn->error;
}
$conn->close();

但只有Twitter会被替换。我是PHP的新手。也许有人可以帮我解决这个问题。谢谢。

2 个答案:

答案 0 :(得分:2)

$conn->query($sql)语句运行您的查询。在运行之前,您将覆盖第一个$sql(Facebook上的那个)。你会做类似的事情

$sql = "UPDATE pm_videos SET `description` = REPLACE(  `description` ,'Facebook',  '')";
if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully with Facebook";
} else {
    echo "Error updating record: " .  $conn->error;
}
$sql = "UPDATE pm_videos SET `description` = REPLACE(  `description` ,'Twitter',  '')";
if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully with Twitter";
} else {
    echo "Error updating record: " .  $conn->error;
}

答案 1 :(得分:2)

您的第一个查询将不会被执行,因为$ sql字符串将被覆盖,并且您最终只会执行第二个查询。

由于您多次执行相同的查询,只更改参数,我建议您使用预处理语句和占位符,如下所示:

$sql = "UPDATE pm_videos SET `description` = REPLACE(`description`, ?,  '')";

$conn = new mysqli($servername,$username, $password, $dbname);
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $content);

$content='facebook';
$stmt->execute();

$content='twitter';
$stmt->execute();

$stmt->close();
$conn->close();

(我删除了所有错误检查,您可能想要添加自己的错误检查例程)。