有没有办法同时更新两个表?我有一个表food
和表food_r
这是我插入食物的代码
$rest_id = null;
if ( !empty($_GET['rest_id']))
{
$rest_id = $_REQUEST['rest_id'];
}
if ( null==$rest_id )
{
echo "null==$rest_id";
}
if(isSet($_POST['submit']))
{
// keep track post values
$food_name = $_POST['food_name'];
$food_description = $_POST['food_description'];
$food_menu = $rest_id;
$usertype = $_SESSION['usertype'];
// update data
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $pdo->prepare("INSERT INTO food ( food_name, food_description, food_menu, usertype )
VALUES (:food_name, :food_description, :food_menu, :usertype)");
$sql->execute(array(
':food_name' => $food_name,
':food_description' => $food_description,
':food_menu' => $food_id,
':usertype' => $_SESSION['usertype']
));
Database::disconnect();
echo "Product added!";
}
现在,如果我想要显示插入的产品,我必须在food_r
的表food_menu
值和usertype
的值中插入。
我怎么能这样做?
更新:它以这种方式工作。感谢@JonathonWisnoski给我指的是交易。。
$pdo->beginTransaction();
$sql = $pdo->prepare("INSERT INTO food ( food_name, food_description, food_menu, usertype )
VALUES (:food_name, :food_description, :food_menu, :usertype)");
$sql->execute(array(
':food_name' => $food_name,
':food_description' => $food_description,
':food_menu' => $rest_id,
':usertype' => $_SESSION['usertype']
));
$lastInsertID = $pdo->lastInsertId();
$sql = $pdo->prepare("INSERT INTO food_r (food_id, usertype)
VALUES (:rest_id, :usertype)");
$sql->execute(array(
':rest_id' => $lastInsertID,
':usertype' => $rest_id
));
$pdo->commit();
答案 0 :(得分:1)
更新:它正在这样工作。感谢@JonathonWisnoski给我指的是交易。。
我还为try{}catch{}
阻止任何错误。
try
{
$pdo->beginTransaction();
$sql = $pdo->prepare("INSERT INTO food ( food_name, food_description, food_menu, usertype )
VALUES (:food_name, :food_description, :food_menu, :usertype)");
$sql->execute(array(
':food_name' => $food_name,
':food_description' => $food_description,
':food_menu' => $rest_id,
':usertype' => $_SESSION['usertype']
));
$lastInsertID = $pdo->lastInsertId();
$sql = $pdo->prepare("INSERT INTO food_r (food_id, usertype)
VALUES (:rest_id, :usertype)");
$sql->execute(array(
':rest_id' => $lastInsertID,
':usertype' => $rest_id
));
$pdo->commit();
}
// any errors from the above database queries will be catched
catch (PDOException $e)
{
// roll back transaction
$pdo->rollback();
// log any errors to file
ExceptionErrorHandler($e);
exit;
}