如果第一条语句被成功执行,请运行第二条语句
我有一个PHP脚本,用于将数据发送到我的数据库。如果SQL语句执行成功我想送一个UPDATE语句看起来像:如果第一条语句被成功执行,请运行第二条语句
UPDATE accounts SET status='1' WHERE user_id='" . $_SESSION['user_id'] ."'
是否有可能运行一个第二份声明,如果成功地执行的第一条语句?如果是,那我该怎么做?
这里是我使用的数据发送到数据库的脚本:如果两个SQL语句执行成功,我想给用户发送到页面../success.php?id='.$id
编辑1
<?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');
}
?>
:
$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');
}
可以。使用的$statement->execute();
if ($statement->execute()) {
// next statement
}
返回值了解更多关于这在documentation。
错误处理
除了上面的例子中,你可以检查错误代码。某些事情肯定会在某个时候出错,所以您将需要执行一些错误处理。检查错误代码并决定相应的操作。
一个小例子:
if ($statement->errorCode() === "00000") {
// everything went well!
} else {
throw new Exception("Something went wrong!");
}
了解更多关于在documentation为好。
小心告诉我我的答案有什么问题? –
我试过你的代码。校长也是一样。当我输入SQL语句时,它不起作用 – John
那么如果是这样的话,请给我们更多有关什么不起作用的细节。只是说它不起作用不会帮助我们帮助你。 –
$stml->execute()
成功返回true。因此,U可以检查
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” – John
我的upvote。你的答案实际上是可行的。不明白为什么这是downvoted。 –
做u试图执行更新查询? –
是的,更新查询正在工作 – John
我看不到这里的$ query2-> execute()。 –