Head First PHP&MySQL笔记(3)
自引用表单的概念是先post到自己,如果没有问题的话就执行相应的代码,否则按照要求来进行信息反馈。好处是可以因此通过"粘性"将之前表单的东西"保存"起来。
<?php if (isset($_POST['submit'])) { $from = 'elmer@makemeelvis.com'; $subject = $_POST['subject'];//POST表单原来的东西 $text = $_POST['elvismail']; $output_form = false;
if (empty($subject) && empty($text)) {//对于出现表单内容为空的逻辑。其中empty表示空,isset(开始)表示有设置过。对于不存在的,是isset为false但empty为true // We know both $subject AND $text are blank echo 'You forgot the email subject and body text.<br />'; $output_form = true; }
if (empty($subject) && (!empty($text))) { echo 'You forgot the email subject.<br />'; $output_form = true; }
if ((!empty($subject)) && empty($text)) { echo 'You forgot the email body text.<br />'; $output_form = true; } } else { $output_form = true; }
if ((!empty($subject)) && (!empty($text))) {//如果都不为空,执行 $dbc = mysqli_connect('data.makemeelvis.com', 'elmer', 'theking', 'elvis_store') or die('Error connecting to MySQL server.');
$query = "SELECT * FROM email_list"; $result = mysqli_query($dbc, $query) or die('Error querying database.');
while ($row = mysqli_fetch_array($result)){ $to = $row['email']; $first_name = $row['first_name']; $last_name = $row['last_name']; $msg = "Dear $first_name $last_name,\n$text"; mail($to, $subject, $msg, 'From:' . $from); echo 'Email sent to: ' . $to . '<br />'; }
mysqli_close($dbc); }
if ($output_form) {//对是否显示表单做判断。 ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">//表单提交给自己。使用全局变量_SERVER['PHP_SELF']若文件结构有改动的时候,维护相对容易 <label for="subject">Subject of email:</label><br /> <input id="subject" name="subject" type="text" value="<?php echo $subject; ?>" size="30" /><br />//如果subject之前没有写,为空;否则,由于被传回当前页面,因此值得到传递,实现"粘性"。下面的text一样 <label for="elvismail">Body of email:</label><br /> <textarea id="elvismail" name="elvismail" rows="8" cols="40"><?php echo $text; ?></textarea><br /> <input type="submit" name="submit" value="Submit" /> </form>
<?php } ?> |