Home >Backend Development >PHP Tutorial >Head First PHP&MySQL study notes (2)
7. Code example
<?php
// addemail.php
$dbc = mysqli_connect('localhost', 'root', '', 'elvis_store')
or die('Error connecting to MySQL server.');
$first_name = $_POST['firstname']; // 从前台获取数据
$last_name = $_POST['lastname'];
$email = $_POST['email'];
$query = "INSERT INTO email_list (first_name, last_name, email) VALUES ('$first_name', '$last_name', '$email')";
mysqli_query($dbc, $query) // 执行SQL语句
or die('Error querying database.');
echo 'Customer added.' . $email;
mysqli_close($dbc);
?>
<pre name="code" class="php"><?php
  // sendemail.php
$from = 'jarray@foxmail.com';
  $subject = $_POST['subject'];
  $text = $_POST['elvismail'];
  $dbc = mysqli_connect('localhost', 'root', '', 'elvis_store')
    or die('Error connecting to MySQL server.');
  $query = "SELECT * FROM email_list";
  $result = mysqli_query($dbc, $query) // 执行SQL语句
    or die('Error querying database.');
  while ($row = mysqli_fetch_array($result)){ // while循环条件是mysqli_fetch_array()函数的返回值
    $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);
?>
<?php
// removeemail.php
 
  $dbc = mysqli_connect('localhost', 'root', '', 'elvis_store')
or die('Error connecting to MySQL server.');
$email = $_POST['email'];
$query = "DELETE FROM email_list WHERE email = '$email'"; // 删除数据库中指定条件的邮件
mysqli_query($dbc, $query)
or die('Error querying database.');
echo 'Customer removed: ' . $email;
mysqli_close($dbc);
?>