mysql的一个基础查询

前台html

<form action="index.php" method="post">
    <select name="type" id="">
        <option value="math">math</option>
        <option value="china">china</option>
        <option value="music">music</option>
        <option value="pe">pe</option>
    </select>
    <input type="submit" value="submit"/>
</form>

php根据前台提交的数据查找mysql的数据

数据库中已经有一个名为book的数据表,字段分别有type,author 和time

<?php
    $type=$_POST['type'];

    //链接数据库
    $db=new mysqli('localhost','root','','books');

  //检测是否链接成功
  if(mysqli_connect_erron()){
    echo 'error connect to mysql server';
    exit;
  } //查询语句 $query="select * from book where type='".$type."'"; //执行查询 $result=$db->query($query); //返回结果的行数 $num_result=$result->num_rows; //循环输出结果的内容 for($i=0;$i<$num_result;$i++){ $rows= $result->fetch_assoc(); echo $rows['type'].'<br/>'; echo $rows['author'].'<br/>'; echo $rows['time']; } // 释放结果集 $result->free(); //关闭数据库 $db->close(); ?>

php根据前台输入的数据向数据库添加数据

<?php
    $type=trim($_POST['type']);
    $author=trim($_POST['author']);
    $time=trim($_POST['time']);

    if(!$type || !$author || !$time){
        echo 'plz enter the full ';
        exit;
    }
    if(!get_magic_quotes_gpc()){
        $type=addslashes($type);
        $author=addslashes($author);
        $time=addslashes($time);
    }
    $db=new mysqli('localhost','root','','books');
    if(mysqli_connect_erron()){
        echo 'cant connect to mysql server';
        exit;
    }
    $query="insert into book values ('".$type."','".$author."','".$time."')";
    $result=$db->query($query);

    if($result){
        echo $db->affected_rows.'books insert into databases';
    }else{
        echo 'an error occurred';
    }

    $db->close();
?>

  

  

  

原文地址:https://www.cnblogs.com/wz0107/p/5097182.html