Head First PHP&MySQL学习笔记(二)

三. 创建与填充数据库

1. Web应用是一个设计用来满足用户某个特定目标的动态网站

2. PHP代码中,SQL语句无需以分号结尾;而MySqL终端的每个SQL语句结尾都要加分号

3. 创建数据库:CREATE DATABASE database_name

    创建表:CREATE TABLE table_name(column_name1 column_type1,column_name2 column_type2,……)

    选择默认数据库:USE database_name

    展示表的结构:DESCRIBE table_name

    删除表:DROP TABLE table_name

    删除数据: DELETE FROM table_name

    新增列:ALTER TABLE table_name ADD column_name column_type

    配合where字句指定范围

4. 对于在MySQL中如何表示yes/no值可能还有异议,char(1)这种方法很直接也很高效

5. ->提示符,是标明你还在输入同一条语句,语句结束并加上分号后MySQL就会执行这条语句

6. mysqli_fetch_array()函数将一个数据行存储在一个数组中    

7. 代码示例

<?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)          
    or die('Error querying database.');

  echo 'Customer added.' . $email;

  mysqli_close($dbc);
?>



<?php  
  // sendemail.php  

  $from = 'elmer@makemeelvis.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)
    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);
?>


<?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);
?>

8. 主键的5大原则:主键的数据不能重复;主键必须有一个值;插入新行时必须设置主键;主键必须尽可能高效;主键值不能改变


阅读更多
文章标签: php 数据库 sql
个人分类: php
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭