警告:这是未经测试的。但是,我认为演示如何以更简洁的方式编写它很重要。特别是,将您的意图分解为特定的函数,每个函数都做一件事并返回结果。这将有助于防止您的代码变得混乱,并使单独测试每个块变得更加容易。
require_once'config.php';
//It is always good to declare stuff like this in a central place
//That way they're easy to change, and you change it everywhere you have that express intent
$SQL_FIND_SUBSCRIPTION = "SELECT * FROM subscribers WHERE email=?";
$SQL_NEW_SUBSCRIPTION = "INSERT INTO subscribers(email) VALUES (?)";
//Functions make testing easy!
static function attemptSubscription($postValues, &$returnMsg) {
if ( isset($postValues['subscribe'])
&& isset($postValues['email']) //be sure to validate both!
{
if (isValidEmail($postValues['email'])) {
subscribe($email);//this syntax may be off.
} else {
$returnMsg = "A valid email address must be provided.";
return false;
}
} else {
$returnMsg = "No subscription was attempted.";
return false;
}
}
//Returns true if the passed parameter is a valid email
static function isValidEmail($email) {
//left as an exercise for the reader.
}
//Assumes a valid email address is being passed
static function subscribe($email, &$returnMsg) {
global $mysql; //sadly, this is the cleanest way possible without using a class.
$stmt=$mysql->prepare($SQL_FIND_SUBSCRIPTION);
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result(); // This lets you reuse stmt
if($stmt->field_count > 0){
//Subscription already exists
$returnMsg = "This subscription already exists.";
return true;
} else {
//Subscription must be added
return addNewSubscription($email, $returnMsg);
}
}
static function addNewSubscription($email, &$returnMsg) {
global $mysql; // :(
$stmt=$mysql->prepare($SQL_NEW_SUBSCRIPTION);
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
if($stmt->affected_rows>0){
$returnMsg = "New subscription successful!";
return true;
} else {
$returnMsg = "New subscription failed.";//you can add more info here if you want
return false;
}
$stmt->close();
}
//now actually execute
$resultMsg = "";
if (attemptSubscription($_POST, $resultMsg)) {
echo "Success! ".$resultMsg;
} else {
echo "Oh no! Failure! ".$resultMsg;
}
// ?> Note that eliding this will help remove nasty hidden characters from the rendered html
查看store_result了解更多信息。
使用这种配置,您可以验证各个命令是否正常工作,而无需首先执行它们嵌套的结构。特别是,验证第二个 sql 查询至关重要:非绑定错误通常是因为列或找不到表。然而,话虽如此,请意识到该prepare()
语句所做的是将查询发送到服务器以检查语法;该查询永远不会重新发送,而是在服务器中保持“加载”状态,直到您告诉它(使用另一条语句)摆脱它。当您随后绑定参数时,该参数将发送到服务器并放入可用槽 ( ?
)。然后,由于此模型,您可以有效地多次执行此查询。
请注意,如果服务器上的查询没有新参数的未绑定槽,则绑定它的尝试将失败。如果服务器上的查询试图引用不可用的变量(例如列名),它也会在这一步失败。
从您提供的详细信息中尚不清楚确切的问题出在哪里,但是如果您以更干净的方式编写代码,调试这些问题将变得容易得多:您的第二个 sql 语句是否不好?是不是您没有从第一条语句中正确释放服务器资源?