我在这里滥用GOTO功能吗?

时间:2017-03-22 00:09:15

标签: php goto

我正在为我的妻子和我建立一个CRM用于我们的业务。我创建了一个有几个目标的页面:

  • 能够在数据库中创建新条目。
  • 能够查看数据库中的现有条目。
  • 能够更新数据库中的现有条目。

我最初有几个php文件执行这些东西,但现在已经使用GOTO函数让代码反弹到我需要运行的不同部分,这取决于在同一页面上发生的事情。

我的问题是,除了看起来凌乱之外,这样做是否有挫折?在未来,我将研究其他更清洁的方法(欢迎提出建议),但这对我来说很有用,我想继续这个项目并开始构建我需要的附加部件。 CRM。如果愿意,可以将其视为测试版。如果我已经做了一些巨大的缺点,我宁愿现在解决它,但如果这至少是温和的合理,我会推进。

这就是我所拥有的:

<?php
// Include Connection Credentials
include("../../comm/com.php");

//Connection to Database
$link = mysqli_connect($servername, $username, $password, $dbname);

// Connection Error Check
if ($link->connect_errno) {
    echo "Sorry, there seems to be a connection issue.";
    exit;
}

// Define Empty Temporary Client ID 
$new_client_id ="";

// Define Empty Success Message
$successful ="";

// Define Empty Error Messages
$firstnameErr ="";
$lastnameErr ="";
$addressErr ="";
$cityErr ="";
$stateErr ="" ;
$zipcodeErr ="";
$phoneErr ="";
$emailErr ="";

// CHECK FOR SEARCH PROCESS
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST['searched'])) {
        $client_id = $_POST['client_id'];
        $buttontxt = "Update";
        goto SearchReturnProcess;
    }
}

// Retrieve Client ID
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST['client_id'])) {
        $buttontxt = "Create Client";
        goto CreatNewClientProcess;
    } else {
        $client_id = $_POST['client_id'];
        $buttontxt = "Update";
        goto UpdateClientProcess;
    }
}

//  CONTINUE FOR NEW CLIENT
CreatNewClientProcess:

// Check For Missing Fields and report
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["firstname"])) {
        $firstnameErr = "First name is a required field - please make entry below";
        goto FinishUpProcess;
    }
    if (empty($_POST["lastname"])) {
        $lastnameErr = "Last name is a required field - please make entry below";
        goto FinishUpProcess;
    }
    if (empty($_POST["email"])) {
        $emailErr = "Email is a required field - please make entry below";
        goto FinishUpProcess;
    }
    if (empty($_POST["phone"])) {
        $phoneErr = "Phone is a required field - please make entry below";
        goto FinishUpProcess;
    }
    if (empty($_POST["address"])) {
        $addressErr = "Address is a required field - please make entry below";
        goto FinishUpProcess;
    }
    if (empty($_POST["city"])) {
        $cityErr = "City is a required field - please make entry below";
        goto FinishUpProcess;
    }
    if (empty($_POST["state"])) {
        $stateErr = "State/Province is a required field - please make entry below";
        goto FinishUpProcess;
    }
    if (empty($_POST["zipcode"])) {
        $zipcodeErr = "Postal code is a required field - please make entry below";
        goto FinishUpProcess;
    }
}

// Prepared Statement For Database Search
if ($stmt = $link->prepare("INSERT INTO client (firstname, lastname, address, city, state, zipcode, phone, email) VALUES (?,?,?,?,?,?,?,?)")){

// Bind Search Variable
$stmt->bind_param('ssssssss', $firstname, $lastname, $address, $city, $state, $zipcode, $phone, $email);

// Define Form Field Input
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$phone = $_POST['phone'];
$email = $_POST['email'];

// Execute the Statement
$stmt->execute();
}

// Close Statment
$stmt->close();

// Report Successful Entry
$successful = "Client Successfully Created!";

// Define New Client ID
$new_client_id = $link->insert_id;

// FINISH NEW CLIENT PROCESS
goto FinishUpProcess;



// CONTINUE FOR SEARCHED PROCESS
SearchReturnProcess:

// Prepared Statement For Database Search
$stmt = $link->prepare("SELECT firstname, lastname, address, city, state, zipcode, phone, email FROM client WHERE client_id=?");

// Bind Client ID into Statement
$stmt->bind_param('s', $client_id);

// Execute the Statement
$stmt->execute();

// Bind Variables to Prepared Statement
$stmt->bind_result($firstname, $lastname, $address, $city, $state, $zipcode, $phone, $email);

//fetch value
$stmt->fetch();

// Close Statment
$stmt->close();

// FINISH SEARCHED PROCESS
goto FinishUpProcess; 



// CONTINUE FOR UPDATE CLIENT PROCESS
UpdateClientProcess:

// Prepared Statement For Database Search
if ($stmt = $link->prepare("UPDATE client SET firstname=?, lastname=?, address=?, city=?, state=?, zipcode=?, phone=?, email=? WHERE client_id=?")){

// Bind Search Variable
$stmt->bind_param('sssssssss', $firstname, $lastname, $address, $city, $state, $zipcode, $phone, $email, $client_id);

// Define Form Field Input
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$client_id = $_POST['client_id'];

// Execute the Statement
$stmt->execute();
}

// Close Statment
$stmt->close();

// Report Successful Update
$successful = "Client Updated Successfully!";

// FINISH UPDATE PROCESS
goto FinishUpProcess; 



// CONTINUE FOR FINISHING UP PROCESS
FinishUpProcess:

// Disconnect from Database 
mysqli_close($link)
?>


<!DOCTYPE html>
<html>
<head>
<title>Client Information</title>
<link rel="stylesheet" href="styles.css">
</head>

<body>

<div class="container">  

<form id="contact" action="" method="post">

<h4>enter client info below</h4>
<font color="red"><?php echo $successful; ?></font>

<fieldset>
<input name="client_id" value="<?php if (empty($_POST['client_id'])) { echo $new_client_id; } else { echo $_POST['client_id']; } ?>" type="hidden">
</fieldset>

<fieldset>
<font color="red"><?php echo $firstnameErr; ?></font>
<input name="firstname" value="<?php if (isset($_POST['client_id'])) { echo $firstname; } else { echo $_POST['firstname']; } ?>" placeholder="First Name" type="text" tabindex="1" autofocus>
</fieldset>

<fieldset>
<font color="red"><?php echo $lastnameErr; ?></font>
<input name="lastname" value="<?php if (isset($_POST['client_id'])) { echo $lastname; } else { echo $_POST['lastname']; } ?>" placeholder="Last Name" type="text" tabindex="2">
</fieldset>

<fieldset>
<font color="red"><?php echo $emailErr; ?></font>
<input name="email" value="<?php if (isset($_POST['client_id'])) { echo $email; } else { echo $_POST['email']; } ?>" placeholder="Email Address" type="email" tabindex="3">
</fieldset>

<fieldset>
<input name="mailinglist" id="checkbox" type="checkbox" checked>
<label>add to the mailing list</label>
</fieldset>

<fieldset>
<font color="red"><?php echo $phoneErr; ?></font>
<input name="phone" value="<?php if (isset($_POST['client_id'])) { echo $phone; } else { echo $_POST['phone']; } ?>" placeholder="Phone Number" type="tel" tabindex="4">
</fieldset>

<fieldset>
<font color="red"><?php echo $addressErr; ?></font>
<input name="address" value="<?php if (isset($_POST['client_id'])) { echo $address; } else { echo $_POST['address']; } ?>" placeholder="Street Address" type="text" tabindex="5">
</fieldset>

<fieldset>
<font color="red"><?php echo $cityErr; ?></font>
<input name="city" value="<?php if (isset($_POST['client_id'])) { echo $city; } else { echo $_POST['city']; } ?>" placeholder="City" type="text" tabindex="6">
</fieldset>

<fieldset>
<font color="red"><?php echo $stateErr; ?></font>
<input name="state" value="<?php if (isset($_POST['client_id'])) { echo $state; } else { echo $_POST['state']; } ?>" placeholder="State/Province" type="text" tabindex="7">
</fieldset>

<fieldset>
<font color="red"><?php echo $zipcodeErr; ?></font>
<input name="zipcode" value="<?php if (isset($_POST['client_id'])) { echo $zipcode; } else { echo $_POST['zipcode']; } ?>" placeholder="Postal Code" type="text" tabindex="8">
</fieldset>

<fieldset>
<font color="red"><?php echo $countryErr; ?></font>
<input name="country" value="<?php if (isset($_POST['client_id'])) { echo $country; } else { echo $_POST['country']; } ?>" placeholder="Country" type="text" tabindex="9">
</fieldset>


<fieldset>
<input name="vegan" type="checkbox">
<label>Vegan or Vegitarian</label>
</fieldset>

<fieldset>
<input name="smoker" type="checkbox">
<label>Smoker</label>
</fieldset>

<fieldset>
<textarea name="client_notes" placeholder="general notes" tabindex="10"></textarea>
</fieldset>

<fieldset>
<button name="submit" type="submit" data-submit="...Sending"><?php echo $buttontxt; ?></button>
</fieldset>


</form>
</div>

</body>

</html>

2 个答案:

答案 0 :(得分:2)

我不确定我是否知道PHP中存在goto。多年来我一直使用(和滥用)我的一部分,但不是最近。关于修复:

1 - 你的许多人(例如,SearchReturnProcess)可以用函数调用替换。而不是使用标签开始一段代码(并使用goto到达那里),创建一个具有相同名称function SearchReturnProcess()的单独函数并将代码放在那里。

2 - 对于错误处理,请使用if elseif

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["firstname"])) {
        $firstnameErr = "First name is a required field - please make entry below";
    } elseif (empty($_POST["lastname"])) {
        $lastnameErr = "Last name is a required field - please make entry below";
    } elseif...

等。 然后,您可以使用else结束该组语句,然后是&#34;没有错误&#34;代码,或者代替一堆单独的错误,您可以创建一个通用错误变量(例如,$fieldErr),并在块之后具有像if ($fieldErr != '')这样的代码来处理错误显示并简单地在一个位置显示错误而不是在每个领域旁边。

答案 1 :(得分:1)

是。

我不会传讲异端邪说和亵渎神灵,但要告诉你大部分的GOTO都是错的。

  1. UpdateClientProcess 即可。这是一个非常奇怪的想法,你必须只为创建验证输入。创建和更新应该始终相同。所以这个是无用的和有害的
  2. 验证例程中的FinishUpProcess。从可用性的角度来看,这很可怕。当受害者的头被固定在滴水龙头下时,有一种古老的中国人折磨。一开始没有害处,它让人们及时疯狂。所以你正在进行验证。为什么不检查所有字段然后立即告诉用户,而不是逐个显示错误?
  3. FinishUpProcess来保存数据。这违反了HTTP协议规则,即在处理POST请求后服务器应该发出一个Location头,使用GET方法重定向客户端。否则,如果客户端刷新页面,则记录将被复制。
  4. 看起来很乱。你这么说。由于其单调的结构,我花了很多时间来导航你的代码来审查它。代码填充是故意发明的。例如,在Python中,您强制使用填充来区分从属代码块。
  5. 此代码的正确结构类似于

    $errors = [];
    if ($_POST) {
        if (empty($_POST["firstname"])) {
            $errors['firstname'] = "First name is a required field - please make entry below";
        }
        // and so on
    
        if (!$errors) {
            if (empty($_POST['client_id'])) {
                // go for insert
            } else {
                // go for update
            }
            header("Location: .");
            exit;
        }
        $firstname = htmlspecialchars($_POST['firstname']);
        // and so on
    }
    if (!$errors ) {
        if (!empty($_GET['client_id'])) {
           // search your data from a GET variable
        } else {
            // define empty variables
        }
    }
    ?>
    <html goes here>