更新语句不起作用,还如何在一个mysql查询中包装两个语句

时间:2014-01-21 00:32:32

标签: php mysql insert transactions insert-update

第一个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");
?>

1 个答案:

答案 0 :(得分:0)

更改为

'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

进一步改进