我有一个PHP脚本,我用它来将数据发送到我的数据库。如果成功执行了SQL语句,我想发送一个类似于:
的UPDATE语句UPDATE accounts SET status='1' WHERE user_id='" . $_SESSION['user_id'] ."'
如果第一个语句成功执行,是否可以运行第二个语句?如果是,那我该怎么做?
以下是我用来将数据发送到数据库的脚本:
<?php
session_start();
if (isset($_GET['id']))
$correct = true;
$firstname = $_POST['firstname'] ;
$lastname = $_POST['lastname'] ;
$_SESSION['user_id'];
$status = $_POST['status'] ;
if($correct){
$db = new PDO('mysql:host=localhost;dbname=db', 'root', '');
$query = "INSERT INTO users(firstname, lastname, user_id, status) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->execute(array($firstname, $lastname, $_SESSION['user_id'], $status));
$id = $db->lastInsertId();
header('Location: ../success.php?id='.$id);
}else{
header('Location: ../error.php');
}
?>
如果两个sql语句都成功执行,我想将用户发送到页面../success.php?id='.$id
修改1:
$query1 = "INSERT INTO users(firstname, lastname, user_id, status) VALUES (?, ?, ?, ?)" ;
$stmt = $db->prepare($query1);
$stmt->execute(array($firstname, $lastname, $_SESSION['user_id'], $status));
// the below code will execute if your insertion is successful
$query2 = "UPDATE accounts SET status='1' WHERE user_id='" . $_SESSION['user_id'] ."'" ;
// set the header location to go to another page
$id = $db->lastInsertId();
header('Location: ../success.php?id='.$id);
}else{
header('Location: ../error.php');
}
答案 0 :(得分:0)
$stml->execute()
成功时返回true。所以,你可以检查
if($correct){
$db = new PDO('mysql:host=localhost;dbname=db', 'root', '');
$query = "INSERT INTO users(firstname, lastname, user_id, status) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$exec = $stmt->execute(array($firstname, $lastname, $_SESSION['user_id'], $status));
if($exec){
....do update query
// set the header location to go to another page
}
}
或者只是你可以这样做
if($correct){
$db = new PDO('mysql:host=localhost;dbname=db', 'root', '');
$query = "INSERT INTO users(firstname, lastname, user_id, status) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$exec = $stmt->execute(array($firstname, $lastname, $_SESSION['user_id'], $status)) or die();
// the below code will execute if your insertion is successful
....do update query
// set the header location to go to another page
}
答案 1 :(得分:-1)
你可以。使用$statement->execute();
if ($statement->execute()) {
// next statement
}
在documentation中了解更多相关信息。
除上述示例外,您还可以查看错误代码。某些事情在某个时刻肯定会出错,因此您需要执行一些错误处理。检查错误代码并确定相应的操作。
一个小例子:
if ($statement->errorCode() === "00000") {
// everything went well!
} else {
throw new Exception("Something went wrong!");
}
在documentation中了解更多相关内容。