我没有正式的编码教学,希望有人能告诉我是否要对我的代码保持谨慎?
// Insert info to the db
if ($stmt = $db_connect->prepare("INSERT INTO db (col1, col2) VALUES (?, ?)")) {
if(!$stmt->execute([$val1, $val2])) {
exit("1:Faild to create deal");
}
// Get last id
$id = (int)$db_connect->lastInsertId();
$stmt->closeCursor();
} else { exit("0:Faild to create deal"); }
// Create the folder
if(!mkdir("folder/folder".$id)) {
if($stmt = $db_connect->prepare("DELETE FROM db WHERE id=?")) {
if(!$stmt->execute([$id])) {
exit("1:Faild to create the directory -> Faild to remove the row from the database");
}
exit("Faild to create the directory");
}
exit("0:Faild to create the directory -> Faild to remove the row from the database");
}
我使用相同的布局重复创建文件夹语句2次。这只是可重复的代码,看起来有点矫枉过正。
注意:我与主机的软件包只有MyISAM表,所以我不能使用Rollback。
如果出现故障,我想撤消已经过去的所有内容。
有人可以给我一些最佳实践的指导,还是我做得对?
答案 0 :(得分:1)
我重新构建并扩展了代码,并通过使用异常添加了一些简单的错误处理。
首先,您应将PDO
错误处理设置为异常模式:
$db_connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
然后我将你的动作封装成函数,你可以将它们放入一个单独的文件中并包含它,甚至将它们嵌入到类中:
/*** FUNCTIONS ***/
// insert info to the db
function dbInsertInfo($db_connect, $val1, $val2)
{
$stmt = $db_connect->prepare("INSERT INTO db (col1, col2) VALUES (?, ?)");
$stmt->execute([$val1, $val2]));
}
//-------------------------------
// get the last insert id
function dbGetId($db_connect)
{
$id = (int)$db_connect->lastInsertId();
$stmt->closeCursor();
return $id;
}
//-------------------------------
// delete db-entry
function dbDeleteId($db_connect, $id)
{
$stmt = $db_connect->prepare("DELETE FROM db WHERE id=?");
$stmt->execute([$id]);
}
//-------------------------------
// create the folder
function createFolder($id)
{
if(!mkdir("folder/folder".$id)) throw new Exception("Failed to create the directory");
}
//-------------------------------
然后,这是您的所有try{ } catch{ }
部分的过程,用于异常处理错误:
/* PROCEDURE */
// 01 | try to insert into db
try
{
dbInsertInfo($db_connect, $val1, $val2);
}
catch(PDOException $e)
{
//if exception thrown, do not continue the script:
echo "Unable to insert into DB: ".$e->getMessage();
exit();
}
//-------------------------------
// 02 | try to get last insert id
$id = false;
try
{
$id = dbGetId($db_connect);
}
catch(PDOException $e)
{
//if exception thrown, do not continue the script:
echo "Unable to get last insert id from DB: ".$e->getMessage();
exit();
}
//-------------------------------
// 03 | try to create folder // if it fails -> try to delete db entry
try
{
createFolder($id);
}
catch(Exception $e)
{
// if exception caught, try to remove the corresponding DB entry:
echo $e->getMessage();
echo "<br />";
echo "trying to remove DB entry now";
// try to delete db entry
try
{
dbDeleteId($db_connect, $id);
}
catch(PDOException $e)
{
//if exception thrown, do not continue the script:
echo "Unable to delete from DB: ".$e->getMessage();
exit();
}
}
//-------------------------------
/* Everything worked fine if you get to this point of the code*/
现在看起来对你来说似乎是一种技术上的矫枉过正,但是一旦你进入它,我认为它更结构化,更好阅读它。另外,它只分为3个步骤。