gpt4 book ai didi

php - 更新语句不起作用,以及如何将两个语句包装在一个 mysql 查询中

转载 作者:行者123 更新时间:2023-11-30 00:47:26 27 4
gpt4 key购买 nike

第一个 mysql 语句看起来不错,但不会运行:

声明:

$sql = "UPDATE ('bands') SET ('Stock' = 'Stock' - 1) WHERE ('Band_id' = '$Band_id')";

我还希望将这个语句和这个语句一起运行:

$sql = "INSERT INTO orders (band_id,user_id,user_name,band_name,band_venue) VALUES('$band_id', '$user_id', '$user_name', '$name', '$venue')";

我知道我需要在事务中执行此操作,但我用谷歌搜索了它,但不明白如何执行此操作。

完整代码

    <?php
require 'core/init.php';
$user = new User();

$Band_id = mysql_real_escape_string($_GET['id']);
$band_id = mysql_real_escape_string($_POST['band']);
$name = mysql_real_escape_string($_POST['bandname']);
$venue = mysql_real_escape_string($_POST['bandvenue']);
$user_id = escape($user->data()->id);
$user_name = escape($user->data()->username);



$sql = "INSERT INTO orders (band_id,user_id,user_name,band_name,band_venue) VALUES('$band_id', '$user_id', '$user_name', '$name', '$venue')";
//$sql = "UPDATE ('bands') SET ('Stock' = 'Stock' - 1) WHERE ('Band_id' = '$Band_id')";

mysql_query ($sql, $linkme)
or die ("could not add to database");
?>

最佳答案

更改为

'UPDATE `bands` SET `Stock` = (`Stock` - 1) WHERE `Band_id` = ' . $Band_id . ')';

如果您使用PDO (你可能应该如此),这就是你所需要的:

$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

$dbh = new PDO($dsn, $user, $password);

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$dbh->beginTransaction();
$dbh->exec('UPDATE `bands` SET `Stock` = (`Stock` - 1) WHERE `Band_id` = ' . $Band_id . ')');
$dbh->exec('INSERT INTO `orders` (`band_id`, `user_id`, `user_name`, `band_name`, `band_venue`) VALUES("'.$band_id.'", "'.$user_id.'", "'.$user_name.'", "'.$name.'", "'.$venue.'")');
$dbh->commit();

您可以使用 prepared statements 进一步改进

关于php - 更新语句不起作用,以及如何将两个语句包装在一个 mysql 查询中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21246948/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com