表单提交

前台正常表单提交

  1. <?php
  2. header('Conten-Type: text/html; charset=utf-8');
  3. $dbms='mysql'; // 数据库类型
  4. $host='localhost'; // 主机名或ip地址
  5. $dbname= 'PHPlesson'; //数据库名称
  6. $user= 'root'; // 用户名
  7. $pass= ''; // 密码
  8. $dsn="$dbms:host=$host;dbname=$dbname"; // 拼接成串
  9. try {
  10. $dbh = new PDO($dsn,$user,$pass);
  11. $newstitle = $_REQUEST["newstitle"];
  12. $newsimg = $_REQUEST["newsimg"];
  13. $newscontent = $_REQUEST["newscontent"];
  14. $addtime = $_REQUEST["addtime"];
  15. $sql = "INSERT INTO `news`(`newstitle`, `newsimg`, `newscontent`, `addtime`) VALUES ('".$newstitle."','".$newsimg."','".$newscontent."','".$addtime."')";
  16. $res = $dbh->exec($sql);
  17. $arr = array('message'=>'添加成功','data'=>[],'code'=>1);
  18. echo json_encode($arr, JSON_UNESCAPED_UNICODE);
  19. $dbh = null;
  20. } catch(PDOException $e){
  21. die("Error:" . $e.getMessage(). "<br>");
  22. }
  23. ?>

这里一定要注意SQL语句里面变量要用拼接字符串的方式连接起来 不然会是空的。

表格查询

前台正常查询表格

  1. <?php
  2. header('Conten-Type: text/html; charset=utf-8');
  3. $dbms='mysql'; // 数据库类型
  4. $host='localhost'; // 主机名或ip地址
  5. $dbname= 'PHPlesson'; //数据库名称
  6. $user= 'root'; // 用户名
  7. $pass= ''; // 密码
  8. $dsn="$dbms:host=$host;dbname=$dbname"; // 拼接成串
  9. try {
  10. $dbh = new PDO($dsn, $user, $pass);
  11. $dbh->query('set names utf8');
  12. $sql = 'SELECT * FROM `news`';
  13. $result = $dbh->query($sql);
  14. $arr = array();
  15. foreach ($result as $row) {
  16. array_push($arr,array('newsid'=>$row['newsid'],'newstitle'=>$row['newstitle'],'newsimg'=>$row['newsimg'],'newscontent'=>$row['newscontent'],'addtime'=>$row['addtime']));
  17. }
  18. $datas = array('code'=>1,'data'=>$arr,'message'=>'查询成功');
  19. echo json_encode($datas);
  20. } catch (PDOException $e) {
  21. die("Error:" . $e.getMessage(). "<br>");
  22. }

这里有两点需要注意,一个是输出的是utf-8的编码,需要$dbh->query('set names utf8');来控制让前台拿到的中文不是乱码,还有一个点就是拿到了数据封装进一个数组内。